简体   繁体   English

使用 JSON 解析时保留引号

[英]Keeping quotation marks when using JSON parse

I've been unable to phrase this question in a way when searching which yields any results, so forgive me if there is an obvious place this has been asked.在搜索会产生任何结果时,我一直无法以某种方式表达这个问题,所以如果有明显的地方被问到,请原谅我。

I'd like all quotation marks to remain in my JSON when converting from a string.从字符串转换时,我希望所有引号都保留在我的 JSON 中。

My UI has a text field (string) which a user will type some JSON which will look something like this:我的 UI 有一个文本字段(字符串),用户将输入一些 JSON,它看起来像这样:

{ "example": "example" }

I'd like all the quotation marks to remain in my JSON object.我希望所有引号都保留在我的 JSON 对象中。 However, when I run JSON.parse() on the above string, I get the following:但是,当我在上面的字符串上运行 JSON.parse() 时,我得到以下信息:

{ example: "example" }

How can I keep the quotation from being removed?如何防止引用被删除?

A javascript object, which is what JSON.parse() returns, is not json. JSON.parse() 返回的 javascript 对象不是 json。 You don't need the quotes in an object (unless there are special characters in the property name) and can access that property with or without quotes in your code您不需要对象中的引号(除非属性名称中有特殊字符)并且可以在代码中使用或不使用引号访问该属性

const myObj = { example: "example" };

Both of the following are valid以下两项均有效

console.log(myObject.example)
console.log(myObject["example"])

When you JSON.stringify() this again it will have valid quotes in the json string and be:当您再次使用 JSON.stringify() 时,它将在 json 字符串中包含有效的引号,并且是:

{ "example": "example" }

JSON.parse() returns a javascript object , so the results you are getting are correct. JSON.parse()返回一个javascript 对象,因此您得到的结果是正确的。

Your backend needs a JSON string , not a javascript object, so you need to JSON.stringify() your javascript object to obtain the JSON string that your backend requires.您的后端需要JSON string ,而不是 javascript 对象,因此您需要JSON.stringify()您的 javascript 对象以获取后端所需的 JSON 字符串。

let userinput = '{ "example": "example" }';
let userobject = JSON.parse(userinput);
let resultjson = JSON.stringify(userobject);

console.log(userinput);
console.log(userobject);
console.log(resultjson);

produces产生

{ "example": "example" } {“示例”:“示例”}
{ example: 'example' } { 示例:'示例' }
{"example":"example"} {“示例”:“示例”}

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

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