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

时间:2016-02-07 18:44:44

标签: javascript json stomp

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

  

“[{\” 名称\ “:\” 测试\ “\ ”版本\“:\ ”1.0.4 \“,\ ”寿命\“:25000}]”

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

  

[{ “名称”: “测试”, “版本”: “1.0.4”, “寿命”:25000}]

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

  

未捕获的TypeError:无法使用'in'运算符在[{“name”:“test”,“version”:“1.0.4”,“lifetime”:25000}]

中搜索'86'

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

这是我的代码:

      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__: 
}

1 个答案:

答案 0 :(得分:0)

由于价值低于[]。你需要经历两个$.each

&#13;
&#13;
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>');
   });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;