浏览复杂的JSON

时间:2016-08-11 08:23:39

标签: javascript jquery json jointjs

首先,请原谅我的英语,我是法国人。

我来找你,因为我有问题。我想帮助在Javascript中使用循环浏览复杂的JSON对象(因为它使用JOINTJS生成自己)但我无法做到。我可以通过json手动完成["细胞"] [" 7"] [" attrs"] ["文字"] [&# 34;文本&#34]。以下是一个元素的JSON示例:

    $arrayToBePrinted = [];
    foreach ($result as $results)
    {
        $final_result= array_add($final_result, 'id', $results->id);
        $final_result= array_add($final_result, 'question', $results->question);
        $final_result= array_add($final_result, 'question_main', $results->question_main);
        $final_result= array_add($final_result, 'options', array(
            [
                1 => $results->option_1,
                2 => $results->option_2,
                3 => $results->option_3,
                4 => $results->option_4,
            ]
        ));

     $arrayToBePrinted[] = $final_result;

    }
    return json_encode($arrayToBePrinted,JSON_PRETTY_PRINT);

并解析JSON:

enter image description here

我会得到"文字":" 230004" (根据项目而变化)。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

您可以像这样访问对象:obj.cells[7].attrs.text.text,其中obj是保存对象的变量。

另请注意,由于cells属性包含数组,您可以循环遍历该数组并分别获取每个单独的值,如下所示:



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);
});