将包含没有双引号的键/值的javascript对象转换为纯JSON

时间:2013-11-06 01:50:28

标签: javascript json

鉴于此对象

Object { value=584, end_time="2013-11-03T07:00:00+0000"}

如何转换为正确的JSON?

JSON.stringify不会在对象中包含键/值的双引号。我得到:

{"value":584,"end_time":"2013-11-03T07:00:00+0000"}

1 个答案:

答案 0 :(得分:0)

当您需要value为“string”类型时,您必须迭代这些项目并转换每个项目的类型。

简单的例子:

objects=[{ value:584},{ value:123},{ value:456}];
console.log('before:',objects);
  //before: [Object { value=584}, Object { value=123}, Object { value=456}]
$.each(objects,function(i,v){objects[i].value = String(v.value)});
console.log('after:',objects);
  //after: [Object { value="584"}, Object { value="123"}, Object { value="456"}]
console.log('JSON-string:',JSON.stringify(objects));
  //JSON-string: [{"value":"584"},{"value":"123"},{"value":"456"}]