嗨,我正在尝试将一个json格式的字符串解码成一个关联数组。字符串是这个字符串:(我的字符串来自一个数据库,它在那里生成)
{
"Parameter1":"<style>
#label-9 {
display: block;
text-align: left;
color: #fff;
}
</style>",
"HistoryPosition":"1"
}当我做json_decode()时,它会给我一个空数组。你知道为什么会这样吗?我相信这是来自"Parameter1“的东西,但找不到它是什么。
谢谢您:)
发布于 2016-05-27 14:58:44
JSONLint表示JSON无效。
您可能要做的是:
$json = '{
"Parameter1":"<style>
#label-9 {
display: block;
text-align: left;
color: #fff;
}
</style>",
"HistoryPosition":"1"
}';
// remove the newlines
$clean = str_replace(["\r", "\n"], ['', ''], $json);
var_dump(json_decode($clean));发布于 2016-05-27 14:57:54
Akshay确实是对的,它是由断线引起的。
<pre><?php
$input = <<<EOD
{
"Parameter1":"<style>
#label-9 {
display: block;
text-align: left;
color: #fff;
}
</style>",
"HistoryPosition":"1"
}
EOD;
// json_decode($input, true);
// echo json_last_error_msg(); // Syntax error
$input = str_replace("\r", null, $input);
$input = str_replace("\n", null, $input);
var_dump(json_decode($input, true));指纹:
array(2) {
["Parameter1"]=> string(176) "<style> #label-9 { display: block; text-align: left; color: #fff; } </style>"
["HistoryPosition"]=> string(1) "1"
}发布于 2016-05-27 15:09:42
与其手写您自己的JSON字符串,您绝对应该使用PHP的内置函数来使您的类似操作至少更容易:
// Use a native PHP array to store your data; it will preserve the new lines
$input = [
"Parameter1" => "<style>
#label-9 {
display: block;
text-align: left;
color: #fff;
}
</style>",
"HistoryPosition" => "1"
];
// This function will preserve everything in your strings
$encoded_value = json_encode($input);
// See your properly formatted JSON string
echo $encoded_value.'<br><br>';
// Decode the string back into an associative PHP array
echo '<pre>';
print_r(json_decode($encoded_value, true));
echo '</pre>';更新数据库检索的新信息
json_last_error_msg();会产生以下错误:
控制字符错误,可能编码错误
如果您不关心保留换行符,那么这样做是可行的:
<?php
$db_data = '{
"Parameter1":"<style>
#label-9 {
display: block;
text-align: left;
color: #fff;
}
</style>",
"HistoryPosition":"1"
}';
$db_data = str_replace("\r", "", $db_data);
$db_data = str_replace("\n", "", $db_data);
echo '<pre>';
print_r(json_decode($db_data, true));
echo '</pre>';https://stackoverflow.com/questions/37486420
复制相似问题