Be careful when using double quotation marks in JSON

  • 2020-03-30 02:16:23
  • OfStack

1. If an attribute in a JSON object contains double quotes, for example
 
{ 
"description": "25"" 
} 

If converted to a string, the backslash is automatically added, changed to "25\", passed to the REST API, and saved to MongoDB.

If the MongoDB shell is used to display this data, it is "25\"", correct.

2. However, if the value is read by the C++ driver, you get "25", so if you return it directly to the browser side, parsing it with jquery.parsejson () will report an error.

When serializing a C++ segment into a string, you need to judge "replace with \".
 
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 JavaScript calls jquery.parsejson () on "25\", the backslash disappears and becomes "25" again.

JavaScript must write code to prevent errors:
 
removeDoubleQuotes: function(str) { 
return str.replace(""", "\""); 
}, 

This is the recurrence of double quotes in JSON. That's a lot of trouble. Be careful.

Related articles: