VBA-tools / VBA-JSON

JSON conversion and parsing for VBA
MIT License
1.76k stars 568 forks source link

Issue to read JSON value with an empty array #178

Closed Magyc closed 4 years ago

Magyc commented 4 years ago

Hi,

I work on JIRA and I fetch a Json file from a query. I have some fields, in particular the "fix version field" which Sometime For exemple, mu Json looks like this :

{ "expand": "schema,names", "startAt": 0, "maxResults": 1000, "total": 1012, "issues": [ { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "id": "2046908", "self": "An URL", "key": "BFIRD-13", "fields": { "fixVersions": [] }, { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "id": "2046461", "self": "https://jira.mycompagnie.com/rest/api/2/issue/2046461", "key": "BFIRD-14", "fields": { "fixVersions": [ { "self": "An URL", "id": "335496", "description": "", "name": "20R6", "archived": false, "released": false } ] } } }, { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "id": "2046908", "self": "An URL", "key": "BFIRD-13978", "fields": { "fixVersions": [] }, { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "id": "2046461", "self": "https://jira.mycompagnie.com/rest/api/2/issue/2046461", "key": "BFIRD-14", "fields": { "fixVersions": [ { "self": "An URL", "id": "335496", "description": "", "name": "20R6", "archived": false, "released": false } ] } } } ] }

Sometime, I have value into fixVersions I it's ok to used the value

Set JsonObject = JsonConverter.ParseJson(sResult) For Each Item In JsonObject("issues") version = Item("fields")("fixVersions")(1)("name") .... .... Next

But if the fixVersions block is empty in my Json, I have an error and I can't seem to get out of it. I tried something like that : For Each Item In JsonObject("issues") If Not Item("fields")("fixVersions")(1)("name") is Nothing Then version = Item("fields")("fixVersions")(1)("name") Else version = "empty" End if .... Next

But I still have an error when the fixVersions is empty in my Json. What is the type of an empty array after Json conversion ? Do you have any idea ?

Regards

timhall commented 4 years ago

When the array is empty, you can't access a value by index, so the (1) in your code is likely causing the issue. You can check if a collection has items with .Count, so your code would likely be:

If Item("fields")("fixVersions").Count > 0 Then
  version = Item("fields")("fixVersions")(1)("name")
Else
  version = "empty"
End if
Magyc commented 4 years ago

Thx dude :) I tried many thing but not the count ... !