无法解析AJAX响应中的嵌套JSON



我在jQuery/AAJAX中写了一段代码来查询Elasticsearch,并根据搜索条件返回文档列表。我可以从Elasticsearch获取文档。我正在尝试解析这些文档并将它们显示在网页中。这是Elasticsearch索引的回复。

{
"took": 12,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 4,
"relation": "eq"
},
"max_score": 1.617034,
"hits": [
{
"_index": "test",
"_type": "_doc",
"_id": "uhp0sW0BO2MOKYEQa-CB",
"_score": 1.617034,
"_source": {
"MsgTime": "2019-10-09T16:57:39.829Z",
"OrganizationID": "nasa",
"UserID": "USER1",
"TravelID": "1234",
"MachineID": "9099",
"Stage": "ingested"
}
},
{
"_index": "test",
"_type": "_doc",
"_id": "sxpnsW0BO2MOKYEQ9eAo",
"_score": 1.617034,
"_source": {
"MsgTime": "2019-10-09T16:44:03.102Z",
"OrganizationID": "nasa",
"UserID": "USER1",
"TravelID": "201710283fc113afa731459285b55d94bb8ddf02",
"MachineID": "9099",
"Stage": "processed"
}
}
]
}
}

对于"hits"下的每个"_source"元素,我试图在网页上实现的输出如下。在适用的情况下,数值会有所不同。

"MsgTime": "2019-10-09T16:57:39.829Z",
"OrganizationID": "nasa",
"UserID": "USER1",
"TravelID": "1234",
"MachineID": "9099",
"Stage": "ingested"

我尝试在jQuery中使用以下代码(只是解析部分(将输出解析为AJAX响应

$(document).ready(function() {
$("#search").click(function() {
var textboxvalue = $("#trip_id").val();                            
$.ajax({
url: myURL,
type: "GET",
dataType: 'json',
data: query = {
q: "TravelID: " +textboxvalue,
pretty:'true',
size:100
},
success: function( result ) { 
$.each( result, function( key, value ) {
$.each(value,function(hits,v){
$.each(v,function(i,hits){
$.each(hits,function(_source,v){
console.log(_source,v);
});
});
});
});

在解析部分中,我无法获得最终输出。我不确定我最后的$.每个循环是否正确。

如果需要,我可以提供更多信息。我在这里排除了HTML。

提前感谢,Nick

我提取了您的解析语句。它基本上可以简化为以下内容:

obj =
{ "took": 12, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4, "relation": "eq" }, "max_score": 1.617034, "hits": [ { "_index": "test", "_type": "_doc", "_id": "uhp0sW0BO2MOKYEQa-CB", "_score": 1.617034, "_source": { "MsgTime": "2019-10-09T16:57:39.829Z", "OrganizationID": "nasa", "UserID": "USER1", "TravelID": "1234", "MachineID": "9099", "Stage": "ingested" } }, { "_index": "test", "_type": "_doc", "_id": "sxpnsW0BO2MOKYEQ9eAo", "_score": 1.617034, "_source": { "MsgTime": "2019-10-09T16:44:03.102Z", "OrganizationID": "nasa", "UserID": "USER1", "TravelID": "201710283fc113afa731459285b55d94bb8ddf02", "MachineID": "9099", "Stage": "processed" } } ] } }
console.log(obj.hits.hits.map(v=>v._source))

在您的JavaScript对象中,您有一个可以直接寻址的对象hits,在该对象中,还可以直接寻址一个数组hits。要获得具有_source属性的包含对象的内容,您需要使用类似于上面显示的.map()的循环技术。

最新更新