如何从stringify对象访问数组

时间:2016-08-25 11:00:58

标签: json

这是使用JSON.stringify()方法创建的json对象。 我无法访问data1(此处的数组)。如何访问和打印它。

{"data1":[{"text":"TMS-1","id":"1.0","children":[{"text":"Services","id":"1.0.0","children":[{"text":"child service","id":"1.0.0.0"}]},{"text":"Applications","id":"1.0.1","children":[]},{"text":"Radios","id":"1.0.2","children":[{"text":"radio child","id":"1.0.2.0","children":[{"text":"child 2","id":"1.0.2.0.0"},{"text":"child 2.1","id":"1.0.2.0.1"},{"text":"child 2.2","id":"1.0.2.0.2"}]},{"text":"radio service1","id":"1.0.2.1","children":[{"text":"child 1.2.1","id":"1.0.2.0.0"}]}]},{"text":"Platform","id":"1.0.3","children":[{"text":"platform child","id":"1.0.3.0"}]},{"text":"Faults","id":"1.0.4","children":[{"text":"Fault child","id":"1.0.4.0"}]}]}]}

2 个答案:

答案 0 :(得分:0)

实现以下代码以获取数组。

try {
        JSONObject jsonObject = new JSONObject(yourResponseString);
        JSONArray jsonArray = jsonObject.getJSONArray("data1");
    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

尝试

var str = JSON.stringify(something); // should be {"data1":[{"text":"TMS-1","id":"1.0","children":[{"text":"Services","id":"1.0.0","children":[{"text":"child service","id":"1.0.0.0"}]},{"text":"Applications","id":"1.0.1","children":[]},{"text":"Radios","id":"1.0.2","children":[{"text":"radio child","id":"1.0.2.0","children":[{"text":"child 2","id":"1.0.2.0.0"},{"text":"child 2.1","id":"1.0.2.0.1"},{"text":"child 2.2","id":"1.0.2.0.2"}]},{"text":"radio service1","id":"1.0.2.1","children":[{"text":"child 1.2.1","id":"1.0.2.0.0"}]}]},{"text":"Platform","id":"1.0.3","children":[{"text":"platform child","id":"1.0.3.0"}]},{"text":"Faults","id":"1.0.4","children":[{"text":"Fault child","id":"1.0.4.0"}]}]}]}
var JsonArray = JSON.parse(str);

了解详情:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse