预期输出应打印键及其值
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]);
}
然而,控制台正在打印
感谢帮助
答案 0 :(得分:0)
首先使用JSON.parse(str)
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