简体   繁体   English

我怎样才能使这个 JSON.stringify 正常工作

[英]How can I make this JSON.stringify work properly

I have a small issue to make my arrays into the json I want to.我有一个小问题要将我的 arrays 变成我想要的 json。 I have made this code:我做了这个代码:

 var arrData = [{label:Test,value:199.12}, {label:Test2,value:1024}] var data = []; for (var i = 0; i < arrData.length; i++) { data.push(JSON.stringify({ label: arrData[i][2], value: arrData[i][3] }).replace(/\"/g, "").replace("\\r", "")) }

It also does the job properly.它也能正确地完成工作。 But I do want it to be in this format:但我确实希望它采用这种格式:

{ label: 'Food', value: 90 }, { label: '食物', 值: 90 },

I want to have the ' ' on the label data and I want to remove the double "" punctuation mark outside the json.我想在 label 数据上有 ' ' 并且我想删除 json 之外的双“”标点符号。 Since my current json looks like this:由于我当前的 json 看起来像这样:

"{label:Test,value:199.12}", "{label:Test2,value:1024}", 

{ label: 'Food', value: 90 } isn't valid JSON so you cannot create it using JSON.stringify . { label: 'Food', value: 90 }无效 JSON 所以你不能使用JSON.stringify创建它。

It isn't any standard serialisation format (although it is a valid JavaScript literal) so if you want to serialise data to it, you'll need to write a custom serialiser.它不是任何标准的序列化格式(尽管它是一个有效的 JavaScript 文字)所以如果你想将数据序列化到它,你需要编写一个自定义序列化器。

You could loop over the properties of the object and append them, the associated values, and whatever quotes and commas your format demands, to a string.您可以将 object 和 append 的属性、关联的值以及格式要求的任何引号和逗号循环到一个字符串。

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

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