Consider using arrays instead of numerated object.

Arrays in json are defined using [] http://www.json.org/

Here is an example:

var foo = {
    "logged_in":true,
    "town":"Dublin",
    "state":"Ohio",
    "country":"USA",
    "products":
    [
        {
            "pic_id":"1500",
            "description":"Picture of a computer",
            "localion":"img.cloudimages.us/2012/06/02/computer.jpg",
            "type":"jpg",
            "childrenimages":
            [
                {
                    "pic_id":"15011",
                    "description":"Picture of a cpu",
                    "localion":"img.cloudimages.us/2012/06/02/mycpu.png",
                    "type":"png"
                },
                {
                    "pic_id":"15012",
                    "description":"Picture of a cpu two",
                    "localion":"img.cloudimages.us/2012/06/02/thiscpu.png",
                    "type":"png"
                }
            ]
        },
        {
            "pic_id":"1501",
            "description":"Picture of a cpu",
            "localion":"img.cloudimages.us/2012/06/02/cpu.png",
            "type":"png"
        }
    ],
};

(Forgive me if I forgot either closing { or [ or , its pretty hard to type code in SO :p )

This way you dont even need to have counts like

"products":2,

or

"childrenimages":2

You simply do

foo.products.length

or

foo.products[0].childrenimages.length

Good luck :)

Answer from Dmitry Kudryavtsev on Stack Overflow
Top answer
1 of 4
23

Consider using arrays instead of numerated object.

Arrays in json are defined using [] http://www.json.org/

Here is an example:

var foo = {
    "logged_in":true,
    "town":"Dublin",
    "state":"Ohio",
    "country":"USA",
    "products":
    [
        {
            "pic_id":"1500",
            "description":"Picture of a computer",
            "localion":"img.cloudimages.us/2012/06/02/computer.jpg",
            "type":"jpg",
            "childrenimages":
            [
                {
                    "pic_id":"15011",
                    "description":"Picture of a cpu",
                    "localion":"img.cloudimages.us/2012/06/02/mycpu.png",
                    "type":"png"
                },
                {
                    "pic_id":"15012",
                    "description":"Picture of a cpu two",
                    "localion":"img.cloudimages.us/2012/06/02/thiscpu.png",
                    "type":"png"
                }
            ]
        },
        {
            "pic_id":"1501",
            "description":"Picture of a cpu",
            "localion":"img.cloudimages.us/2012/06/02/cpu.png",
            "type":"png"
        }
    ],
};

(Forgive me if I forgot either closing { or [ or , its pretty hard to type code in SO :p )

This way you dont even need to have counts like

"products":2,

or

"childrenimages":2

You simply do

foo.products.length

or

foo.products[0].childrenimages.length

Good luck :)

2 of 4
3

That's not actually an array that you have there, that's just an object containing properties that are also objects. You're also missing a few commas so this won't even compile.

What might be more convenient for you in this case is to use both arrays and objects to form your JSON. For Example:

 var this_json_string = {
    "state":"Ohio",
    "country":"USA",
    "products":[
        {
          "pic_id":"1500",
          "description":"Picture of a computer",
        },

        {
          "pic_id":"15011",
          "description":"Picture of a cpu"
        },
        {
          "pic_id":"15012",
          "description":"Picture of a cpu two"
        },
        {
          "pic_id":"1501",
          "description":"Picture of a cpu"
        }
    ]
};
🌐
RestfulAPI
restfulapi.net › home › json › json array
JSON Array - Multi-dimensional Array in JSON
November 4, 2023 - JSON Array is a list of items surrounded by square brackets. Each item in the array is separated by a comma. Learn about multi-dimensional arrays.
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Array multidimensional to JSON - Programming - Arduino Forum
August 2, 2023 - I have two dimensional array from sensor reading, id and time_update. for an example i write loop to adding value to array like this : String biDimArray[5][2]; void setup() { // put your setup code here, to run once…
🌐
Oracle
docs.oracle.com › en › cloud › paas › integration-cloud › rest-adapter › homogenous-multidimensional-array-support-json-documents.html
Homogenous Multidimensional Array Support in JSON Documents
November 15, 2024 - While converting XML elements back into JSON, the injected elements are converted into JSON with nested arrays. The following JSON document consists of a multidimensional array (@ref "rercordsData”).
🌐
IBM
ibm.com › docs › en › app-connect › 11.0.0
Graphically modeling a multidimensional JSON array in a ...
In the Graphical Data Mapping editor, you can use the Add User-Defined function to create a multidimensional JSON array, also known as a nested JSON array.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Iterate elements in multidimensional JSON array
July 10, 2019 - Tell us what’s happening: I m trying to iterate entire JSON array newData and want to update a field in it. Your code so far var newData=JSON.parse(success); console.log(newData) console.log(elementsName) const data1 = newData[0].results.recordset[0].ElementList; // console.log(data1.toArray()); var array=JSON.parse(data1) array.forEach(function(element){ ...
Top answer
1 of 2
8

an object literal has no .length

you can count properties using this method:

var count = 0;

for (i in jsonString) {
    if (jsonString.hasOwnProperty(i)) {
        count++;
    }
}

alert(count); //count shall have length for you

OR

since your array didn't have numeric indices (starting from 0), it assumed you used an associative array, hence they dumped an object of items rather than an array of items.

to turn them to numeric indices, all you have to do is use array_values before encoding them to json:

json_encode(array_values($array));

then the json will be an array.. then you can use length

from this:

Array(
[1] => Array(
        [product_id] => 1
        [product_model] => HFJ5G1.5
        [product_type] => plat
        [product_return] => graviteits
    )
[2] => Array(
        [product_id] => 2
        [product_model] => HHJ5S2.5
        [product_type] => holle plunjer
        [product_return] => veer       
    )
);

it becomes this using array_values(), note the indexes per item:

Array(
[0] => Array(
        [product_id] => 1
        [product_model] => HFJ5G1.5
        [product_type] => plat
        [product_return] => graviteits
    )
[1] => Array(
        [product_id] => 2
        [product_model] => HHJ5S2.5
        [product_type] => holle plunjer
        [product_return] => veer       
    )
);

then encoded to json and stored to jsonString:

jsonString = [
    {
        "product_id": "1",
        "product_model": "HFJ5G1.5",
        "product_type": "plat",
        "product_return": "graviteits"
    },
    {
        "product_id": "2",
        "product_model": "HHJ5S2.5",
        "product_type": "holle plunjer",
        "product_return": "veer"
    }
];

alert(jsonString.length);
2 of 2
1

Objects do not support length property: alert({}.length); gives undefined and alert([].length); gives 0. To find the 'length' of the top level you could do it like:

var arr ={"1":{"product_id":"1","product_model":"HFJ5G1.5",
                 "product_type":"plat","product_return":"graviteits"},
          "2":{"product_id":"2","product_model":"HHJ5S2.5",
                "product_type":"holle plunjer","product_return":"veer"}};
var len = 0;
for(var i in arr) len++;
alert(len);

http://jsfiddle.net/uszaV/

🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
In JSON, array values must be of type string, number, object, array, boolean or null.
Find elsewhere
🌐
GitHub
gist.github.com › glebcha › 8819424
Parse JSON array and create multi-dimensional array · GitHub
Parse JSON array and create multi-dimensional array · Raw · parse JSON.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
SitePoint
sitepoint.com › php
Building custom JSON data with variable multidimensional arrays - PHP - SitePoint Forums | Web Development & Design Community
February 13, 2015 - The way that I thought to be able to handle this is if a unknown array was passed in, wherever it would include a [ and ] brackets I could detect it with php and honour the rule to keep it unquoted. The other { } don’t need to go into the array, they can follow rules and be added as needed or be subject to json_encode and will work well.
🌐
Swift Forums
forums.swift.org › using swift
Getting JSON from database multidimensional array - Using Swift - Swift Forums
November 7, 2018 - Hey All, I am new to swift and i am having some issues with my JSON request. I am able to retrieve the data and i can output this into my ViewController but a part of the data i get back from my database is inside a mul…
🌐
Unity
answers.unity.com › questions & answers
JSON to object for multidimensional array - Questions & Answers ...
August 14, 2018 - For a webgl game we are making for a school project we have to implement localization. We decided to do this with google sheets. But we cannot get the result parsed correctly. We are doing a get request to: https://sheets.googleapis.com/v4/spreadsheets/[FILE_ID]/values/A1:D4?key=[API_KEY]&prettyPrint=false.
🌐
W3Schools
w3schools.io › file › json-cheatsheet
JSON cheatsheet complete tutorial with examples - w3schools
This tutorial covers JSON cheatsheet with examples of empty json null json 2-dimensional arrays nested object array of objects sample json.
🌐
Microsoft Community
community.fabric.microsoft.com › t5 › Power-Query › Parsing-Multi-Dimensional-Array-from-json-API › td-p › 1642449
Solved: Parsing Multi-Dimensional Array from json API? - Microsoft Fabric Community
February 3, 2021 - let YourJson = "{""total_found"":3, ""purchase_ids"":{""444636"":""444636"", ""444637"":""444637"", ""444638"": ""444638""}}", ReadJson = Json.Document(YourJson), CreateTable = Record.ToTable(ReadJson[#"purchase_ids"]) in CreateTable
🌐
Unity
discussions.unity.com › unity engine
Multidimensional array to JSON - Unity Engine - Unity Discussions
February 22, 2021 - Hi, so apparently, since unity does not support 2d array serialization, it can not be saved as json. Everything clear so far. I am, however, curious about one thing in the documentation : “If you want to serialize these, you have two options: wrap the nested type in a class or struct”… Well, that was the plan anyway and i went: [System.Serializable] public class SaveFile { public int x = 0; public int[,] array = new int[2,2]; } And then: using System.Collections; using System.Coll...
🌐
Reddit
reddit.com › r/excel › turning a json multidimensional array into an excel
r/excel on Reddit: Turning a json multidimensional array into an excel
August 2, 2024 -

Hey sorry if this is not the right sub, I am having an issue with this multidimensional json array that I want to turn into an excel table but whenever I do so, it only shows the first two dimensions which I really don't care about and it would be such a hassle to go through the file and delete every dimension and sign that I don't care about.

here is what the file looks like and I am only interested in the transit size:

{"step": {"p2p": {}, "collective": {"hcom_allReduce__852_0_1@5136442222858339852": {"Communication Time Info": {"Start Timestamp(us)": 1722279519921441.0, "Elapse Time(ms)": 12.6548, "Transit Time(ms)": 4.160679999999999, "Wait Time(ms)": 0.4504600000000002, "Synchronization Time(ms)": 2e-05, "Idle Time(ms)": 8.043660000000001, "Wait Time Ratio": 0.0977, "Synchronization Time Ratio": 0.0}, "Communication Bandwidth Info": {"RDMA": {"Transit Size(MB)": 0, "Transit Time(ms)": 0, "Bandwidth(GB/s)": 0, "Large Packet Ratio": 0, "Size Distribution": {}}, "HCCS": {"Transit Size(MB)": 469.7620479999989, "Transit Time(ms)": 29.189260000000015, "Bandwidth(GB/s)": 16.0937, "Large Packet Ratio": 0.0, "Size Distribution": {"2.097152": [224, 29.189260000000015]}}, "PCIE": {"Transit Size(MB)": 0, "Transit Time(ms)": 0, "Bandwidth(GB/s)": 0, "Large Packet Ratio": 0, "Size Distribution": {}}, "SDMA": {"Transit Size(MB)": 469.7620479999989, "Transit Time(ms)": 29.189260000000015, "Bandwidth(GB/s)": 16.0937, "Large Packet Ratio": 0, "Size Distribution": {}}, "SIO": {"Transit Size(MB)": 0, "Transit Time(ms)": 0, "Bandwidth(GB/s)": 0, "Large Packet Ratio": 0, "Size Distribution": {}}}}}}}
🌐
W3Docs
w3docs.com › php
JSON_ENCODE of multidimensional array giving different results
<?php $data = [ "name" => "John Doe", "address" => [ "street" => "123 Main St", "city" => "Anytown", "state" => "CA", "zip" => "12345", ], "phone numbers" => [ "home" => "555-555-5555", "work" => "555-555-5556", ], ]; $json = json_encode($data); echo $json; ... After executing the code, you can see the sub-arrays "address" and "phone numbers" have been converted into JSON objects.
🌐
SitePoint
sitepoint.com › php
PHP Multidimensional json array - PHP - SitePoint Forums | Web Development & Design Community
May 4, 2012 - Like I said in my first post the json data must be in the same format but able to loop through. ... No, you’ll need to change your code that writes the data out, as you only have one query now you can only have one mysql_fetch_array statement.