rcdmk / aspJSON

A fast classic ASP JSON parser and encoder for easy JSON manipulation to work with the new JavaScript MV* libraries and frameworks.
MIT License
203 stars 89 forks source link

Nested Json Objects #25

Closed RaviRamDhali closed 7 years ago

RaviRamDhali commented 7 years ago

I am trying to create the following Json object which has some nested items

[
    {
      "coordinates": [32.850098, -117.2742608],
      "title": "Cove",
      "fillColor": "#fcf8e3",
      "anchor": {
                         "x": 22,
                          "y": 0
                       }
    }
  ]

My code sample is:

set JSON = New JSONobject
 ' add properties
JSON.Add "coordinates", objMaplabel.coordinates
JSON.Add "title", objMaplabel.title
JSON.Add "fillColor", objMaplabel.fillColor
JSON.Add "anchor" ?????????? <-- nested items

How do I add nested json objects ?

rcdmk commented 7 years ago

Hi.

You will have to instantiate a new JSONObject and set the property:

Set anchor = new JSONObject
anchor.add "x", 22
anchor.add "y", 0

JSON.add "anchor", anchor

The README and the test.asp page has some practical examples. Check it out.

RaviRamDhali commented 7 years ago

Thanks --

The following code worked great.

        ' instantiate the class
    set JSON = New JSONobject
    ' add properties
    JSON.Add "coordinates", objMaplabel.coordinates
    JSON.Add "title", objMaplabel.title
    JSON.Add "fillColor", objMaplabel.fillColor

    Dim anchor
    Set anchor = new JSONObject
    anchor.add "x", objMaplabel.anchor_x
    anchor.add "y", objMaplabel.anchor_y

    JSON.add "anchor", anchor

Result

{"coordinates":"[32.850098, -117.2742608]","title":"Cove","fillColor":"black","anchor":{"x":"22.00","y":"0.00"}}

Rolf-Herbert commented 7 years ago

Thanks for the class.

**EDIT - should have checked first..canonical names work

so

obj("data")("subdata")("subsubdata") works for the below example.**

Is there a way to quickly access nested elements instead of creating new objects for each nested level for instance..

{ "data": { "subdata": { "singleprop": 0, "subsubdata": { "id": 1, "name": "Joe" } } } }

Whats the quickest way to get to the ID without doing

obj1 = obj("data") obj2 = obj1("subdata") obj3 = obj2("subsubdata") value = obj3("id")

Thanks again

rcdmk commented 7 years ago

Hi.

Yes, you can chain property calls if you doesn't need another objects properties.

In case you need to access another property values, it's best to get the property object. You are not instantiating in this case, but assigning the property to another variable as a ref. The object graph is already created when you access it.