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

How to extract a JSON object from the resulting JSON array?

本文关键字:JSON 数组 提取 对象      更新时间:2023-09-26

我有以下代码来获取查询结果。查询结果采用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);

请提供建议。

更新

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

试试这个:

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