Lucatorze Lucatorze - 3 months ago 12
Javascript Question

Browsing a complex JSON

first of all, excuse me for my English, I'm French.

I am coming to you because I have a problem. I would like help browsing a complex JSON object with a loop in Javascript (because it generates itself with JOINTJS) but I am not being able to do it. I can do it manually by json [ "cells"] ["7"] ["attrs"] ["text"] ["text"]. Here is an example of JSON for one element:

{"cells":[
{
"type":"basic.Image",
"position":{
"x":50,
"y":350
},
"size":
{
"width":100,
"height":50
},
"angle":0,
"id":"4a2802a8-0bd6-4d06-9343-921092a1decd",
"z":1,
"attrs":{
"text":{
"text":"230004",
"fill":"black"
},
"image":{
"xlink:href":"/uploads/documents/computer.png",
"width":100,
"height":50
}
}
}
]}


and parse JSON :

enter image description here

I would get the "text": "230004" (which changes depending on the item).

Thank you in advance for your help !

Answer

You can access the object like this: obj.cells[7].attrs.text.text, where obj is a variable holding the object.

Also note that as the cells property holds an array, you can loop through that array and get each individual value separately, like this:

var obj = {
  "cells": [{
    "type": "basic.Image",
    "position": {
      "x": 50,
      "y": 350
    },
    "size": {
      "width": 100,
      "height": 50
    },
    "angle": 0,
    "id": "4a2802a8-0bd6-4d06-9343-921092a1decd",
    "z": 1,
    "attrs": {
      "text": {
        "text": "230004",
        "fill": "black"
      },
      "image": {
        "xlink:href": "/uploads/documents/computer.png",
        "width": 100,
        "height": 50
      }
    }
  }, {
    "type": "basic.Image",
    "position": {
      "x": 50,
      "y": 350
    },
    "size": {
      "width": 100,
      "height": 50
    },
    "angle": 0,
    "id": "4a2802a8-0bd6-4d06-9343-921092a1decd",
    "z": 1,
    "attrs": {
      "text": {
        "text": "230005",
        "fill": "black"
      },
      "image": {
        "xlink:href": "/uploads/documents/computer.png",
        "width": 100,
        "height": 50
      }
    }
  }, {
    "type": "basic.Image",
    "position": {
      "x": 50,
      "y": 350
    },
    "size": {
      "width": 100,
      "height": 50
    },
    "angle": 0,
    "id": "4a2802a8-0bd6-4d06-9343-921092a1decd",
    "z": 1,
    "attrs": {
      "text": {
        "text": "230006",
        "fill": "black"
      },
      "image": {
        "xlink:href": "/uploads/documents/computer.png",
        "width": 100,
        "height": 50
      }
    }
  }]
}

obj.cells.forEach(function(cell) {
  console.log(cell.attrs.text.text);
});