使用console.log(对象)并迭代对象键时,JSON键不同

时间:2017-04-10 19:31:41

标签: javascript json node.js express

我从服务器收到的JSON对象遇到了一些问题。在JSON对象上使用console.log正确地显示了我从服务器发送的JSON对象,但是当我尝试迭代键时,它开始表现奇怪。见下文。

> console.log(promotions);
{"promotion1":{"color":"white","backgroundColor":"red","text":"from promotion server"},"promotion2":{"color":"purple","backgroundColor":"yellow","text":"from promotion server2"},"promotion3":{"color":"green","backgroundColor":"black","text":"from promotion server3"}}

> for (p in promotions) { console.log(p); }
0
1
2
3
4
... (continues)
264
265
266
bold
strip
stripColors
trap
zalgo
zebra
rainbow
random
america
reset
dim
italic
underline
inverse
hidden
strikethrough
black
... (continues)
magentaBG
cyanBG
whiteBG

更多细节:

我正在使用http.request向ExpressJS服务器发送请求到另一个ExpressJS服务器,然后返回"促销" JSON对象。我无法判断它是否以某种方式被破坏(我可能设置了错误的编码?)。

使用相同的JSON对象进行测试但硬编码而不是从其他服务器发送,会给出正确的响应。

谢谢!

2 个答案:

答案 0 :(得分:4)

您的promotions值是JSON的字符串表示形式。因此,当你执行for循环时,它会以字符串形式迭代它。

var promotions = '{"promotion1":{"color":"white","backgroundColor":"red","text":"from promotion server"},"promotion2":{"color":"purple","backgroundColor":"yellow","text":"from promotion server2"},"promotion3":{"color":"green","backgroundColor":"black","text":"from promotion server3"}}';

for (var p in promotions) {
  console.log(p);
}

为什么会这样做,请参阅此related question(尽管事实是它只是一个奇怪的结果,因为字符串是幕后的数组,在这种情况下你应该看this answer)< / p>

如果你这样做

var promotions = '{"promotion1":{"color":"white","backgroundColor":"red","text":"from promotion server"},"promotion2":{"color":"purple","backgroundColor":"yellow","text":"from promotion server2"},"promotion3":{"color":"green","backgroundColor":"black","text":"from promotion server3"}}';
  
// convert string representation of JSON into actual object
var promotionsObject = JSON.parse(promotions);

for (var p in promotionsObject) {
  console.log(p);
}

它应该按预期工作。请记住,如果你想浏览每个对象,并打印出那些对象的属性,你需要做额外的工作。见Printing nested JSON without using variable names

答案 1 :(得分:0)

尝试过滤掉属于原型的属性

&#13;
&#13;
[2017-03-22T20:40:03Z]|zl75848|info|id: c37a6657-2f97-4955-8756-09d94beacdba|actor.CIS|ENTITYID_1:1490215203745:[object Object]
&#13;
&#13;
&#13;