XanderMan XanderMan - 7 months ago 17
Javascript Question

Jquery Parsing Multidimensional arrays with sub arrays

I have an API that returns this array or object in JSON

{"orderHead":["51817","frode","","","els"],
"orderLines":[{"VareNr":"07,1437","Produkt":"Black Glue","Antall":"6","Pris":"239","Rabatt":"0%"},{"VareNr":"07,1435","Produkt":"Grey Glue","Antall":"8","Pris":"239","Rabatt":"0%"}],
"orderSum":[{"doc":"26042016_4.oln","knr":"51817","firma":"Tolga Co","oldV":1,"oldS":2868,"newV":0,"newS":0,"newSc":2}]}


As far as I can tell there's three main posts:


  • orderHead

  • orderLines

  • orderSum



Each of which contains their own sub-array.
Problem is I cannot retrieve any data from it, without or without $.parseJSON();

I have tried $.grep and $.each.

Do I have to combine several "tools" to read from this object / array ?
Sorry for the very very noob question :)

Answer

You can parse the JSON with the JSON.parse method

Given the following JSON

{
    "orderHead": [
        "51817",
        "frode",
        "",
        "",
        "els"
    ],
    "orderLines": [
        {
            "VareNr": "07,1437",
            "Produkt": "Black Glue",
            "Antall": "6",
            "Pris": "239",
            "Rabatt": "0%"
        },
        {
            "VareNr": "07,1435",
            "Produkt": "Grey Glue",
            "Antall": "8",
            "Pris": "239",
            "Rabatt": "0%"
        }
    ],
    "orderSum": [
        {
            "doc": "26042016_4.oln",
            "knr": "51817",
            "firma": "Tolga Co",
            "oldV": 1,
            "oldS": 2868,
            "newV": 0,
            "newS": 0,
            "newSc": 2
        }
    ]
}

You can access the values like so:

var json = '{"orderHead":["51817","frode","","","els"],\
"orderLines":[{"VareNr":"07,1437","Produkt":"Black\ Glue","Antall":"6","Pris":"239","Rabatt":"0%"},{"VareNr":"07,1435","Produkt":"Grey\ Glue","Antall":"8","Pris":"239","Rabatt":"0%"}],\
"orderSum":[{"doc":"26042016_4.oln","knr":"51817","firma":"Tolga\ Co","oldV":1,"oldS":2868,"newV":0,"newS":0,"newSc":2}]}';

var parsed = JSON.parse(json);

console.log(parsed.orderHead);

for (line of parsed.orderLines) {
  console.log(line.VareNr, line.Produkt, line.Pris);
}

Returns:

["51817", "frode", "", "", "els"]
07,1437 Black Glue 239
07,1435 Grey Glue 239

You can also access/iterate over the result like so:

// read order sum values
console.log(parsed.orderSum[0].doc, parsed.orderSum[0].knr, parsed.orderSum[0].firma);

// iterate over the order lines
for(line in parsed.orderLines) {
    console.log(parsed.orderLines[line].Produkt);
}

Which returns:

Black Glue
VM132:60 Grey Glue

Comments