Be careful when using double quotation marks in JSON _ javascript tips-js tutorial

Source: Internet
Author: User
If an attribute in a JSON object contains double quotation marks and is converted to a string, a backslash is automatically added. For details, see article 1. If an attribute in a JSON object contains double quotation marks, for example

The Code is as follows:


{
"Description": "25 ""
}


If it is converted to a string, a backslash is automatically added to the string format to "25 \", and then passed to the rest api and saved to MongoDB.

If you use the MongoDB shell to display the data, the value is "25 \", correct.

2. however, if the value is read using C ++ driver, "25" is obtained. Therefore, if you directly return the value to the browser, use jQuery. if parseJSON () is used for parsing, an error is returned.

When the C ++ segment is serialized into a string, you need to judge and replace "\".

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 JavaScript calls jQuery for "25. after parseJSON (), the backslash disappears and becomes "25 "". if you call jQuery again for this attribute value. if pareseJSON is used, an error occurs again.

JavaScript code must be written to prevent errors:

The Code is as follows:


RemoveDoubleQuotes: function (str ){
Return str. replace ("\"","\\\"");
},


This is the cycle of double quotation marks in JSON. Please be careful.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.