0

在我的 MySQL 数据库中,我有以下行:

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

如果我将其导入 JSON,我将得到:

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

这将在 JSONLint 中生成错误:

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

为什么下面的代码不会在 JSONLint 中产生错误?

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

以及如何从 MySQL 导入数据(通过 PHP)以获得上述结果?

4

1 回答 1

1

在 MySQL 的结果集上使用json_encode(PHP 中的内置函数)。

小例子

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

输出

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

该函数会在 JSONLint 接收数据之前清理您发送给它的所有数据。

阅读更多关于json_encode的内容。

于 2012-08-26T16:57:46.267 回答