gpt4 book ai didi

javascript - 从 stomp 消息响应中迭代 json 数组 (JavaScript)

转载 作者:行者123 更新时间:2023-11-28 06:24:17 25 4
gpt4 key购买 nike

我从 STOMP 订阅收到消息正文响应,如下所示:

"[{\"name\":\"test\",\"version\":\"1.0.4\",\"lifetime\":25000}]"

为了迭代它,我将其解析为 json 并得到:

[{"name":"test","version":"1.0.4","lifetime":25000}]

现在,当我尝试迭代它时,我收到以下错误消息:

Uncaught TypeError: Cannot use 'in' operator to search for '86' in [{"name":"test","version":"1.0.4","lifetime":25000}]

任何人都可以帮助我并说出我做错了什么吗?

这是我的代码:

      stompClient.subscribe('/topic/validation', function(validationMessage){

console.log(validationMessage.body);
// --> "[{\"name\":\"test\",\"version\":\"1.0.4\",\"lifetime\":25000}]"
var jsonObj = JSON.parse(validationMessage.body);
console.log(jsonObj);
// --> [{"name":"test","version":"1.0.4","lifetime":25000}]

$.each(jsonObj, function(i,item){
console.log(item);
});
});

提前致谢。

validationMessage 的控制台日志:

Frame{
ack: (headers)arguments: nullcaller: nulllength: 1name: ""prototype: frame.ack__proto__: ()<function scope>
body: ""[{\"name\":\"test\",\"version\":\"1.0.4\",\"lifetime\":25000}]""
command: "MESSAGE"
headers: Object
content-length: "99"
content-type: "application/json;charset=UTF-8"
destination: "/topic/validation"
message-id: "1dm_aduc-1672"
subscription: "sub-0"__proto__: Objectnack: (headers)__proto__:
}

最佳答案

因为该值位于[]下。你需要经过两个 $.each

var jsonObj = [{"name":"test","version":"1.0.4","lifetime":25000}];
$.each(jsonObj, function(){
$.each(this, function(i,item){
$('body').append('<div>'+ item +'</div>');
});
});

var jsonObj2 = {"name":"test","version":"1.0.4","lifetime":25000}; // no []
$.each(jsonObj2 , function(i,item){
$('body').append('<div>'+ item +'</div>');
});

//////////////////////////////////////////////////////////////


var jsonObj3 = JSON.parse('[{\"name\":\"test\",\"version\":\"1.0.4\",\"lifetime\":25000}]');

$.each(jsonObj3, function(){
$.each(this, function(i,item){
$('body').append('<div>'+ item +'</div>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - 从 stomp 消息响应中迭代 json 数组 (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35257543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com