简体   繁体   中英

How to import escaped data from MySQL to JSON?

In my MySQL database I have the folowing row:

\\"test\\" | \\'test\\' | \\'test\\' \\"test\\"

If I import that to JSON I will get that:

[
    "\"test\"",
    "\'test\'",
    "\'test\' \"test\""
]

which will generate erron in JSONLint:

Parse error on line 2:
...    "\"test\"",    "\'test\'",    "\'t
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

Why the below code doesn't generate error in JSONLint?

[
    "\"test\"",
    "\\'test\\'",
    "\\'test\\' \"test\""
]

And how to import data (by PHP) from MySQL to get the above result?

Use json_encode (a built in function in PHP) on the resultset from MySQL.

Small example

$a = Array(
    '\"test\"',
    '\'test\'',
    '\'test\' \"test\"'
);
echo json_encode($a);

Outputs

[
    "\"test\"",
    "'test'",
    "'test' \"test\""
]

The function cleans up any data you send to it before JSONLint receives the data.

Read up more on json_encode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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