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

enhanced JSON parse examples #40

Closed gufmar closed 7 years ago

gufmar commented 7 years ago

May I ask for some "best practice" on how to parse deeper data structures?

For example the given JSON is { "mystring": "test", "datapoints":[ { "x":123, "y":456, "value":"val1" }, { "x":156, "y":234, "value":"val2" } ]}

first JSON.Parse(jsonString) then push the content/value of datapoints into an array Dim JSONarr = New JSONarray JSONarr.Push JSON.value("datapoints") now I would expect that the JSONarr has an two items that I can loop trough and load in a JSONdataset object ... { "x":123, "y":456, "value":"val1" }, { "x":156, "y":234, "value":"val2" } but JSONarr has only one item (index:0) and JSONarr.write() prints out [[{ "x":123, "y":456, "value":"val1" },{ "x":156, "y":234, "value":"val2" }]] so it seems that the array was not "pushed" as an array but as a whole single string.

what I'm missing or doing wrong here?

rv-rsouza commented 7 years ago

Hi.

If you need to get a reference to the "datapoints" array you have to access the value directly. It's already a JSONarray object when parsed:

<%
' ...
set arr = JSON("datapoints") ' datapoints type is JSONarray

for each item in arr
    ' item type is JSONobject
    response.write item("x") & ", " & item("y") & ": " & item("value") & "<br>"
next
%>

The way you expected didn't worked because Push() adds an item to the array, so your code added an array to a new array, outputting a nested array.

rcdmk commented 7 years ago

Hey @gufmar,

Have you solved this?

gufmar commented 7 years ago

@rcdmk yes with your example things became clear given this JSON

{
  "name": "basic name",
  "number": 12345,
  "datapoints":[
        { "x":123, "y":456, "senderMbps":"10.0", "receiverMbps":"15.6",  "signals":[
            { "SSID":"myWifi", "clients":5 },
            { "SSID":"AndroidAP", "clients":2 }
        ] },
        { "x":156, "y":234, "senderMbps":"14.2", "receiverMbps":"12.4",  "signals":[
            { "SSID":"myWifi", "clients":7 },
            { "SSID":"AndroidAP", "clients":2 }
        ] }
    ]
}

this piece of code gave me access to all elements in the arrays

<%
myname = JSON.Value("name")
set JSONDatapoints = JSON("datapoints")
for i = 0 to JSONDatapoints.length - 1
    myX = JSONDatapoints(i).value("x")
    myY = JSONDatapoints(i).value("y")
    mySpeed = JSONDatapoints(i).value("receiverMbps")
    set JSONSignals = JSONDatapoints(i).value("signals")
    for i = 0 to JSONSignals.length - 1
        clientNumber = JSONSignals(j).value("clients")
    next
next
%>
rcdmk commented 7 years ago

Great! Closing this one.