尝试打印Json键值但索引正在打印

时间:2016-09-11 08:18:09

标签: javascript jquery json

预期输出应打印键及其值

var myData = '{"is_bot":"No","device":"desktop","brand":"Sony","brand_model":"Vaio","os":"GNU\/Linux","os_version":"15.5","browser":"Chrome","browser_version":"52.0","ua_string":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/52.0.2743.82 Safari\/537.36"}'
    for (var key in myData) {
       console.log(' name=' + key + ' value=' + myData[key]);
    }

然而,控制台正在打印

Console Output

感谢帮助

4 个答案:

答案 0 :(得分:0)

首先使用JSON.parse(str)

将字符串解析为JSON

var myData = '{"is_bot":"No","device":"desktop","brand":"Sony","brand_model":"Vaio","os":"GNU\/Linux","os_version":"15.5","browser":"Chrome","browser_version":"52.0","ua_string":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/52.0.2743.82 Safari\/537.36"}';

   myData = JSON.parse(myData);

    for (var key in myData) {
       console.log(' name=' + key + ' value=' + myData[key]);
    }

答案 1 :(得分:0)

您需要将字符串解析为实际的javascript对象。您看到的结果是因为您正在迭代字符串。



var raw = '{"is_bot":"No","device":"desktop","brand":"Sony","brand_model":"Vaio","os":"GNU\/Linux","os_version":"15.5","browser":"Chrome","browser_version":"52.0","ua_string":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/52.0.2743.82 Safari\/537.36"}';

var data = JSON.parse(raw);

for (var key in data) {
    console.log(' name=' + key + ' value=' + data[key]);
}




答案 2 :(得分:0)

关键是将JSON作为字符串读取 - 您需要从中删除单引号'以使其成为Ojbect

像这样:

var myData = {"is_bot":"No","device":"desktop","brand":"Sony","brand_model":"Vaio","os":"GNU\/Linux","os_version":"15.5","browser":"Chrome","browser_version":"52.0","ua_string":"Mozilla\/5.0 (X11; Linux x86_64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/52.0.2743.82 Safari\/537.36"}

答案 3 :(得分:0)

您正在迭代字符串中的每个字符,因为这是一个字符串而不是对象。

 var myData = JSON.parse(myData);

 Object.keys(myData).forEach(function(key) {
    console.log(' name=' + key + ' value=' + myData[key]); 
 });

有关Object.keys的详情,请查看this link