Json Parsing

Started by Michael Greer, November 01, 2024, 03:50:21 PM

Previous topic - Next topic

Michael Greer

I am retrieving a Json that in part looks like this:
{
  "VItemID": "6137",
  "Extra Data": {
    "Number Of Bulbs": {
      "6": {
        "desc": "6",
        "iconbase": null,
        "icon": null,
        "units": "Bulbs"
      }
    }
  }
}

I cannot figure out how to address the data in the "Number of Bulbs" section.

Loren Doornek

Use DIM(KEY ...) to get the names of the JSON fields.  Below is an example using your data.  The odd thing is that the one level is "#6" instead of just "6" - I've never seen that before!

0010 BEGIN
0020 LET json$=$7B22564974656D4944223A2236313337222C2245787472612044617461223A7B224E756D626572204F662042756C6273223A7B2236223A7B2264657363223A2236222C2269636F6E62617365223A6E756C6C2C2269636F6E223A6E756C6C2C22756E697473223A2242756C6273227D7D7D7D$
0030 DIM LOAD arr${ALL}=json$
0040 LET c=DIM(READ NUM(arr$))
0050 FOR i=1 TO c
0060 PRINT "arr$["+QUO+DIM(KEY arr$)+QUO+"] = "+arr$
0070 NEXT

RUN
arr$["VItemID"] = 6137
arr$["Extra Data.Number Of Bulbs.#6.desc"] = 6
arr$["Extra Data.Number Of Bulbs.#6.iconbase"] = null
arr$["Extra Data.Number Of Bulbs.#6.icon"] = null
arr$["Extra Data.Number Of Bulbs.#6.units"] = Bulbs

Loren Doornek

The "#6" is likely due to the fact that the format ".6" in PXP would indicate the 6th item in an array.  Eg:

Line.1.amount
Line.2.amount
...
Line.6.amount

Since you have a new element named "6", the JSON parser in PXP would normally create that as "Extra Data.Number of Bulbs.6.desc", but that would be confusing since it addressing it as such would indicate an array. 

My suggestion would be that you prefix or suffix something with the 6 so that it isn't just a raw number.

Michael Greer

Loren - Thanks. This gave me what I needed (had to tweak the code just a bit).  This is not *my* json but is returned by a 3rd party. I agree with you that the ".6" looks like an array element.  I tried ""6"" but to no avail.  The #6 is working.