简体   繁体   English

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

[英]Convert javascript object containg keys/values without double quotes to pure JSON

Given this object 给定这个对象

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

How do I convert to proper JSON? 如何转换为正确的JSON?

JSON.stringify doesn't wrap double-quotes around keys/values without them in the object. JSON.stringify不会将双引号引起来的键/值不包含在对象中。 I just get: 我得到:

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

When you need value to be of type "string" you must iterate over the items and convert the type of each single item. 当需要将value的类型设置为“字符串”时,必须遍历所有项目并转换每个单个项目的类型。

simple example: 简单的例子:

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"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM