The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword

You don't have any comments in your JSON, but you should remove the var and start like this:

orders: {

The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

Also, the empty object labs should be filled with something.

Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)

Update 2 answered:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

returns 'aspirin'. It is however better suited for foreaches everywhere

Answer from Corkscreewe on Stack Overflow
Top answer
1 of 5
25

The first code is an example of Javascript code, which is similar, however not JSON. JSON would not have 1) comments and 2) the var keyword

You don't have any comments in your JSON, but you should remove the var and start like this:

orders: {

The [{}] notation means "object in an array" and is not what you need everywhere. It is not an error, but it's too complicated for some purposes. AssociatedDrug should work well as an object:

"associatedDrug": {
                "name":"asprin",
                "dose":"",
                "strength":"500 mg"
          }

Also, the empty object labs should be filled with something.

Other than that, your code is okay. You can either paste it into javascript, or use the JSON.parse() method, or any other parsing method (please don't use eval)

Update 2 answered:

obj.problems[0].Diabetes[0].medications[0].medicationsClasses[0].className[0].associatedDrug[0].name

returns 'aspirin'. It is however better suited for foreaches everywhere

2 of 5
19

I successfully solved my problem. Here is my code:

The complex JSON object:

   {
    "medications":[{
            "aceInhibitors":[{
                "name":"lisinopril",
                "strength":"10 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "antianginal":[{
                "name":"nitroglycerin",
                "strength":"0.4 mg Sublingual Tab",
                "dose":"1 tab",
                "route":"SL",
                "sig":"q15min PRN",
                "pillCount":"#30",
                "refills":"Refill 1"
            }],
            "anticoagulants":[{
                "name":"warfarin sodium",
                "strength":"3 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "betaBlocker":[{
                "name":"metoprolol tartrate",
                "strength":"25 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "diuretic":[{
                "name":"furosemide",
                "strength":"40 mg Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }],
            "mineral":[{
                "name":"potassium chloride ER",
                "strength":"10 mEq Tab",
                "dose":"1 tab",
                "route":"PO",
                "sig":"daily",
                "pillCount":"#90",
                "refills":"Refill 3"
            }]
        }
    ],
    "labs":[{
        "name":"Arterial Blood Gas",
        "time":"Today",
        "location":"Main Hospital Lab"      
        },
        {
        "name":"BMP",
        "time":"Today",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"BNP",
        "time":"3 Weeks",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"BUN",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Cardiac Enzymes",
        "time":"Today",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"CBC",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Creatinine",
        "time":"1 Year",
        "location":"Main Hospital Lab"  
        },
        {
        "name":"Electrolyte Panel",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"Glucose",
        "time":"1 Year",
        "location":"Main Hospital Lab"  
        },
        {
        "name":"PT/INR",
        "time":"3 Weeks",
        "location":"Primary Care Clinic"    
        },
        {
        "name":"PTT",
        "time":"3 Weeks",
        "location":"Coumadin Clinic"    
        },
        {
        "name":"TSH",
        "time":"1 Year",
        "location":"Primary Care Clinic"    
        }
    ],
    "imaging":[{
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        },
        {
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        },
        {
        "name":"Chest X-Ray",
        "time":"Today",
        "location":"Main Hospital Radiology"    
        }
    ]
}

The jQuery code to grab the data and display it on my webpage:

$(document).ready(function() {
var items = [];

$.getJSON('labOrders.json', function(json) {
  $.each(json.medications, function(index, orders) {
    $.each(this, function() {
        $.each(this, function() {
            items.push('<div class="row">'+this.name+"\t"+this.strength+"\t"+this.dose+"\t"+this.route+"\t"+this.sig+"\t"+this.pillCount+"\t"+this.refills+'</div>'+"\n");
        });
    });
  });

  $('<div>', {
    "class":'loaded',
    html:items.join('')
  }).appendTo("body");

});

});

🌐
Phrase
support.phrase.com › hc › en-us › articles › 6111330881692--JSON-Nested-Strings
.JSON - Nested (Strings) – Phrase
Nested JSON is a .JSON file with a large portion of values being other .JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity by decoupling objects into different layers, making it easier to maintain. Keys are stored by separating levels with a dot ..
Discussions

How can I access a nested array within a JSON file?
To access a nested array within a JSON file, you can traverse the JSON structure using the array index notation. For example, let’s say your JSON data resembles this structure: {"data": [["apple", "banana"], ["car", "bike"]]}. To retrieve the item “car”, you’d navigate using data[1][0]. ... More on community.latenode.com
🌐 community.latenode.com
0
0
October 29, 2024
Create nested array with json object with form-data
Hello there. For a couple of days now, I try to create a nested array and have an object inside that array where I can set text key/value pairs while simultaneously uploading files (hence form-data). In the end, I want… More on community.postman.com
🌐 community.postman.com
3
0
August 20, 2020
JSON - Working with Nested Arrays and Collections
My goal is to upload this JSON data from Apple Health into AirTable every day 👇 Here’s my OUTPUT: output.json (5.9 KB) But I don’t have access to the qty 👇 In AirTable, I will have different columns like this: From this data sample, for example, I want to have: 1220.075000000023 go ... More on community.make.com
🌐 community.make.com
3
0
January 31, 2024
JSON Object parsing with nested Array
Hello all, I tried to parse json below and I was able to get these nested ID but I was able to deserialize json and create json object but now I’m not able to "enter in events array. Can anyone help? Big thansk in advan… More on forum.uipath.com
🌐 forum.uipath.com
13
0
April 30, 2019
🌐
Liquid-technologies
blog.liquid-technologies.com › advanced-data-structures-in-json-part-3-of-4
Advanced Data Structures in JSON: Nested Objects & Arrays
July 4, 2025 - Visualizing these nested structures is key, and tools like the graphical JSON viewer in Liquid Studio JSON Editor can be invaluable for navigating and understanding complex hierarchies. Often, you need to represent a list or collection of items, where each item is itself a complex entity with multiple attributes. This is achieved using an array of objects.
🌐
Qlik Community
community.qlik.com › t5 › Member-Articles › Parsing-Nested-JSON-Objects › ta-p › 2535112
Parsing: Nested JSON Objects - Qlik Community - 2535112
November 4, 2025 - Unlike the previous post Parsing: Flat JSON - Field Value Pairs this structure has more than just the fields and values it has entity structure. The · name field isn't a standalone name, it's part of the ... sheriff's office isn't just a field ... it's a nested entity, that includes multiple field value pairs.
🌐
Adobe
opensource.adobe.com › Spry › samples › data_region › JSONDataSetSample.html
JSON Data Set Sample
The JSON output from different Server APIs can range from simple to highly nested and complex. The examples on this page attempt to illustrate how the JSON Data Set treats specific formats, and gives examples of the different constructor options that allow the user to tweak its behavior. See our JSON Primer for more information. Example 1 - JSON Array with simple data types as elements.
Find elsewhere
🌐
Latenode
community.latenode.com › other questions › javascript
How can I access a nested array within a JSON file?
October 29, 2024 - To access a nested array within a JSON file, you can traverse the JSON structure using the array index notation. For example, let’s say your JSON data resembles this structure: {"data": [["apple", "banana"], ["car", "bike"]]}. To retrieve ...
🌐
Medium
medium.com › @ferzia_firdousi › multi-level-nested-json-82d29dd9528
Deeply Nested JSON, json.normalize, pd.read_json | Medium
May 3, 2023 - Reading the JSON into a pandas object shows that _df[‘students’] is a multi-level nested key-value pair enclosed in a list, whereas _df[‘school_name’] and _df[‘class’] are single key-value pairs (multi-level key-value pair is only one format: list).
🌐
CodeSignal
codesignal.com › learn › courses › parsing-json-with-csharp › lessons › parsing-json-arrays-and-nested-structures
Parsing JSON Arrays and Nested Structures
Similarly, each department contains another array called employees. To parse this nested structure, we use a nested loop approach, where the outer loop processes the departments and the inner loop traverses through each employee within those departments:
🌐
Postman
community.postman.com › help hub
Create nested array with json object with form-data - Help Hub - Postman Community
August 20, 2020 - Hello there. For a couple of days now, I try to create a nested array and have an object inside that array where I can set text key/value pairs while simultaneously uploading files (hence form-data). In the end, I want the following object: {media: [{media: file, type: video}, {media: file1, type: photo]} The way I tried to achieve this, and which I still think should be the way to go: media[0][type]:photo media[0][media]:file media[1][type]:video media[1][media]:file1 but this doesnt end u...
🌐
Make Community
community.make.com › questions
JSON - Working with Nested Arrays and Collections - Questions - Make Community
January 31, 2024 - My goal is to upload this JSON data from Apple Health into AirTable every day 👇 Here’s my OUTPUT: output.json (5.9 KB) But I don’t have access to the qty 👇 In AirTable, I will have different columns like this: From this data sample, for example, I want to have: 1220.075000000023 go into Active Energy (kcal) using the name active_energy as a filter.
🌐
UiPath Community
forum.uipath.com › help
JSON Object parsing with nested Array - Help - UiPath Community Forum
Hello all, I tried to parse json below and I was able to get these nested ID but I was able to deserialize json and create json object but now I’m not able to "enter in events array. Can anyone help? Big thansk in advance { “sportId”: 33, “last”: 210756101, “league”: [ { “id”: 204735, “name”: “ATP Challenger Seoul - R2”, “events”: [ { “id”: 982609151, “starts”: “2019-05-01T02:00:00Z”, “home”: “Yan Bai”, “away”: “Evgeny Donskoy”, “rotNum”: “9359”, “liveStatus”: 0, “status”: “I”, ...
Published: April 30, 2019
🌐
Reddit
reddit.com › r/javascript › building a nested json array from divs that aren't nested?
r/javascript on Reddit: Building a nested JSON array from divs that aren't nested?
November 25, 2015 -

Hi guys,

I'm working on something at the minute that is giving me a lot of grief. Basically I'm using bootstrap and jQuery to design a webpage and its got to the point where I'm sending JSON over the network to save to a hibernate back end. All of the objects are set up fine and are working, but I'm looking for a "better" solution to generate the JSON than the one I've currently got. The relationships are like this:

Parent -> Child -> GrandChild
      `-> Child -> GrandChild

All of the mappings are one to many relationships, and the way the divs are laid out on the screen is basically like this:

<div id="left">
    <div id="parent"></div>
    <div id="Child"></div>
    <div id="GrandChild"></div>
</div>
<div id="right">
    <div id="Child"></div>
    <div id="GrandChild"></div>
</div>

(again you can have many "Child" divs, and many "GrandChild" divs between each "Child" div, and the same for the right side - the nesting actually goes deeper than this, but if I can figure out this to start with then I can adapt it).

What I am doing at the minute is when the user presses "Save" is to build the JSON tree by renaming the name element of every input in every div in order for the mapping to work when I seriallize the whole page. What I am finding is that this requires a horrendous function to essentially loop through all of the divs and reset counters whenever a new parent object is encountered. For example assume (on the left side):

<div id="left">
    <div id="Parent"></div>
    <div id="Child"></div>
    <div id="GrandChild"></div>
    <div id="GrandChild"></div>
    <div id="GrandChild"></div>
    <div id="Child"></div>
    <div id="GrandChild"></div>
</div>

My javscript would essentially do this (pseudocode):

childCounter = -1;
grandChildCounter = -1;

for each div {
   if div == Parent { skip };
   if div == Child { childCounter +=1; grandChildCounter = -1; childDiv.name = childArray[childCounter] };
   if div == GrandChild { grandChildCounter += 1; grandChildDiv.name = childArray[childCounter].grandChildArray[grandChildCounter] };
}

Obviously with more nested levels this kind of code just gets insane... so I've been trying to generate the JSON array recursively by building everyone's children beforehand and appending it to the object as an array - but I run into the same issue of needing manually traverse down the nest just to append the array of children to their correct parent. Either way seems cumbersome and produces really sloppy code - I am new to javascript and jQuery so I do wonder if I'm going about this whole thing the wrong way and am looking for some advice.

I'm also sorry about the lack of proper code but the work isn't at home. Thanks in advance

Top answer
1 of 1
3
First problem I see is that you have duplicates of the same ID. IDs must be unique to the current document, so I would suggest using a class name instead to classify each div as a parent, child, grandchild, etc. Once you have that out of the way, why use the DOM as a visual representation of some object state rather than trying to derive a desired state from the structure of the DOM? This way, you can model your data in pure javascript and JSONify the structure to send to your backend server while also adding in the necessary hooks to render it to the DOM. Im not sure what your data structure needs to look like, but here's a pretty simple example: function Person(name){ this.name = name; this.children = []; this.siblings } // person -> instance of a Person object Person.prototype.addChild(person){ this.children.push(person); } // Convert objects to object literals Person.prototype.toJSON = function(){ return { name: this.name, children: this.children.map(function(person){ return person.toJSON(); }) }; }; var bob = new Person('Bob'); var stacy = new Person('Stacy'); var john = new Person('John'); var jsonBob = bob.toJSON(); /* { name: 'Bob', children: [ { name: 'Stacy', children: [ { name: 'John', children: [] } ] } ] } */ stacy.addChild(john); bob.addChild(stacy); In this case Bob is Stacy's parent, and John is Stacy's child, making John also the grandchild of Bob. Basically you're building a tree of nodes where each node represents a person. Also not sure what you're trying to do with the data once it's stored, but this general structure is probably flexible enough to do whatever you can think of. Hopefully this helps a little bit. edit: formatting and words
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 186609 › json-nested-array-data-as-string-value
JSON Nested Array data as String value - Microsoft Q&A
I used Advanced editor section in mapping field to capture the entire array field using wildcard '*'. ... Thank you for the sample data @Kunal Kumar Sinha . The preferred way to handle this type of deeply nested JSON is a 2-step process.
🌐
Claris Community
community.claris.com › en › s › question › 0D50H00007kmC43SAE › create-nested-json
Create nested JSON
March 5, 2020 - Yes, hope to have time to do that - time spent working on JSON is probably well invested. ... I had a similar question the other day and got good help here. This is how you would set up the code to build the array: ... However, like @wimdecorte (Partner)​ points out, you might want to build each element separately and then join them all together at the end, just to make things more manageable. For each nested object within a nested array you would increase the number by one, JSON always starts with 0 as the first point.
🌐
Reddit
reddit.com › r/csharp › nested arrays in json response
r/csharp on Reddit: Nested arrays in json response
December 6, 2021 -

Hi everyone,

How can I get the "value" from the "legs" array from google directions api using Newtonsoft.Json.
I do the following but it returns 0.

        public static async Task LoadHotelDistance()
        {
            HttpClient client = new HttpClient();

            string url = "https://maps.googleapis.com/maps/api/directions/json?origin=Disneyland&destination=Universal+Studios+Hollywood&key=&&&&&&";
            string response = await client.GetStringAsync(url);
            Distance distance = JsonConvert.DeserializeObject<Distance>(response);
            string hotelDistance = distance.value.ToString();
            MessageBox.Show(hotelDistance);
        }

        public class Distance
        {
            public string text { get; set; }
            public int value { get; set; }
        }

        public class Leg
        {
            public Distance distance { get; set; }
            public Duration duration { get; set; }
            public string end_address { get; set; }
            public string start_address { get; set; }
            public List<Step> steps { get; set; }
            public List<object> traffic_speed_entry { get; set; }
            public List<object> via_waypoint { get; set; }
        }

full response: https://developers.google.com/maps/documentation/directions/quickstart#api-key

Many thanks in advance.

Top answer
1 of 2
2
JsonConvert.DeserializeObject() is the inverse of JsonConvert.SerializeObject(). The DeserializeObject() method expects to receive JSON that looks like what you would get if you called SerializeObject() on an object of that exact same type. In this case, the Distance class members would need to be annotated, and the JSON file would only have a "text" string and a "value" number, and nothing else. To query a small part of a larger JSON file, you need to do something more like this.
2 of 2
1
There is an example of the response in the documentation. You can just take the example and parse it through https://json2csharp.com/ to create a class which matches. It results in this: // Root myDeserializedClass = JsonConvert.DeserializeObject(myJsonResponse); public class GeocodedWaypoint { public string geocoder_status { get; set; } public string place_id { get; set; } public List types { get; set; } public bool? partial_match { get; set; } } public class Northeast { public double lat { get; set; } public double lng { get; set; } } public class Southwest { public double lat { get; set; } public double lng { get; set; } } public class Bounds { public Northeast northeast { get; set; } public Southwest southwest { get; set; } } public class Distance { public string text { get; set; } public int value { get; set; } } public class Duration { public string text { get; set; } public int value { get; set; } } public class EndLocation { public double lat { get; set; } public double lng { get; set; } } public class StartLocation { public double lat { get; set; } public double lng { get; set; } } public class Leg { public Distance distance { get; set; } public Duration duration { get; set; } public string end_address { get; set; } public EndLocation end_location { get; set; } public string start_address { get; set; } public StartLocation start_location { get; set; } } public class OverviewPolyline { public string points { get; set; } } public class Route { public Bounds bounds { get; set; } public string copyrights { get; set; } public List legs { get; set; } public OverviewPolyline overview_polyline { get; set; } public string summary { get; set; } public List warnings { get; set; } public List waypoint_order { get; set; } } public class Root { public List geocoded_waypoints { get; set; } public List routes { get; set; } public string status { get; set; } } You can then just use var data = JsonConvert.DeSerialize(response);
🌐
Postman
community.postman.com › help hub
How to do a assertion on a nested JSON array? - Help Hub - Postman Community
September 1, 2023 - Hi, I am looking for assertion ... how response looks like. { "response": { "entities": [ { "id": "d8410b29b305", "type": "SKU", "data": { "attributes": { "businessConditions": { "group": [ { ......