如何从生成的JSON数组中提取JSON对象?

时间:2015-03-04 19:03:25

标签: javascript jquery json

我有以下代码来获取查询结果。查询结果采用JSON格式。

$.ajax({
    url: ..... //url//...,
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({
        "type": "daysofyear",
        "entity": {
            "year": "2015"
        }
    }),
    type: "POST",
    dataType: "json",
    success: function(result) {
        if ((result) && (result.isSuccess == true)) {
            alert("SUCCESS");
            alert(json.entity.day);
        }
    },
});

返回的JSON是:

{
    "isSuccess": true,
    "results": [{
        "jsonClass": "RuleSuccess",
        "message": "Found mapping for year: 2015",
        "rule": {
            "name": "Year rule",
            "metadata": {}
        },
        "entity": {
            "year": "2015",
            "month": "December",
            "day": "Saturday"
        }
    }]
}

我基本上试图分别提取月,年,日的值,并使用

单独显示它们
alert(json.entity.day);

请建议。

2 个答案:

答案 0 :(得分:3)

<强>更新

var a =JSON.parse('{"isSuccess":true,"results":[{"jsonClass":"RuleSuccess","message":"Found mapping for year: 2015","rule": {"name":"Year rule","metadata":{}}, "entity":{"year":"2015", "month":"December",  "day":"Saturday"}}]}') ;


alert(a.results[0].entity.day);

<强>原始

使用

alert(result[0].rule.entity.day);

答案 1 :(得分:0)

试试这个:

obj = JSON.parse(json);
console.log(obj[0].rule.entity.day);