Home > Web Front-end > JS Tutorial > Be careful when using double quotes in JSON_javascript skills

Be careful when using double quotes in JSON_javascript skills

WBOY
Release: 2016-05-16 16:56:55
Original
1161 people have browsed it

1. If there are attributes in the JSON object that contain double quotes, such as

Copy the code The code is as follows:

{
"description": "25""
}

If converted into string form, a backslash will be added automatically and become "25"", Then pass it to the REST API and save it to MongoDB.

If you use the MongoDB shell to display the data at this time, it will be "25"", which is correct.

2. But if you use the C driver to read this value, you will get "25"" , so if you return it directly to the browser and use jQuery.parseJSON() to parse it, an error will be reported.

When serializing segment C into a string, you need to make a judgment and replace "with".
Copy code The code is as follows:

void string_to_json_string(std::string const& str, std::string & json_str) {
std::stringstream ss;
for (size_t i = 0; i < str.length(); i) {
if (str[i] == '"') {
ss << '\' << '"';
} else {
ss << str[i];
}
}
json_str = ss.str();
}

3. If After JavaScript calls jQuery.parseJSON() on "25"", the backslash has disappeared and changed to "25"". If jQuery.pareseJSON is called on the attribute value again, an error will occur again.

JavaScript must write code to prevent errors:
Copy code The code is as follows:

removeDoubleQuotes: function(str) {
return str.replace(""", "\"");
},

This is the reincarnation of double quotes in JSON. It's troublesome enough, be careful.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template