Solver
Solver

Reputation: 169

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?

Upvotes: 0

Views: 175

Answers (1)

Henrik Ammer
Henrik Ammer

Reputation: 1899

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.

Upvotes: 1

Related Questions