[英]PHP: json_decode not working
This does not work:这不起作用:
$jsonDecode = json_decode($jsonData, TRUE);
However if I copy the string from $jsonData
and put it inside the decode function manually it does work.但是,如果我从
$jsonData
复制字符串并将其手动放入解码 function 中,它确实可以工作。
This works :这有效:
$jsonDecode = json_decode('{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}', TRUE);
I did output $jsonData
copied it and put in like above in the decode function.我做了 output
$jsonData
复制它并像上面一样放入解码 function 中。 Then it worked.然后它起作用了。 However if I put
$jsonData
directly in the decode function it does not.但是,如果我将
$jsonData
直接放在解码 function 中,则不会。
var_dump($jsonData)
shows: var_dump($jsonData)
显示:
string(144) "{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}"
The $jsonData
comes from a encrypted $_GET
variable. $jsonData
来自加密的$_GET
变量。 To encrypt it I use this:为了加密它,我使用这个:
$key = "SOME KEY";
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB, $iv);
$iv = rawurlencode(base64_encode($iv));
$enc = rawurlencode(base64_encode($enc));
//To Decrypt
$iv = base64_decode(rawurldecode($_GET['i']));
$enc = base64_decode(rawurldecode($_GET['e']));
$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB, $iv);
some time there is issue of html entities, for example \" it will represent like this \" , so you must need to parse the html entites to real text, that you can do using html_entity_decode() method of php.有时会出现 html 实体的问题,例如\"它会像这样表示\" ,因此您必须将 html 实体解析为真实文本,您可以使用 php 的html_entity_decode()方法来做到这一点。
$jsonData = stripslashes(html_entity_decode($jsonData));
$k=json_decode($jsonData,true);
print_r($k);
Most likely you need to strip off the padding from your decrypted data.您很可能需要从解密数据中去除填充。 There are 124 visible characters in your string but
var_dump
reports 144. Which means 20 characters of padding needs to be removed (a series of "\0" bytes at the end of your string).您的字符串中有 124 个可见字符,但
var_dump
报告 144 个。这意味着需要删除 20 个填充字符(字符串末尾的一系列“\0”字节)。
Probably that's 4 "\0" bytes at the end of a block + an empty 16-bytes block (to mark the end of the data).可能是块末尾的 4 个“\0”字节 + 一个空的 16 字节块(标记数据的结尾)。
How are you currently decrypting/encrypting your string?您目前如何解密/加密您的字符串?
Edit :编辑:
You need to add this to trim the zero bytes at the end of the string:您需要添加它以修剪字符串末尾的零字节:
$jsonData = rtrim($jsonData, "\0");
You have to use preg_replace for avoiding the null results from json_decode您必须使用 preg_replace 来避免 json_decode 的空结果
here is the example code这是示例代码
$json_string = stripslashes(html_entity_decode($json_string));
$bookingdata = json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
从其他评论来看,你可以使用,
$jsonDecode = json_decode(trim($jsonData), TRUE);
While moving on php 7.1 I encountered with json_decode error number 4 (json syntex error).在继续使用 php 7.1 时,我遇到了 json_decode 错误号 4(json 语法错误)。 None of the above solution on this page worked for me.
此页面上的上述解决方案均不适合我。
After doing some more searching i found solution at https://stackoverflow.com/a/15423899/1545384 and its working for me.在做了更多搜索后,我在https://stackoverflow.com/a/15423899/1545384找到了解决方案,它对我有用。
//Remove UTF8 Bom
function remove_utf8_bom($text)
{
$bom = pack('H*','EFBBBF');
$text = preg_replace("/^$bom/", '', $text);
return $text;
}
确保将标头设置为 JSON
header('Content-type: application/json;');
str_replace( "\t" , " ", str_replace( "\n" , " ", $string)) str_replace( "\t" , " ", str_replace( "\n" , " ", $string))
because json_decode does not work with special characters.因为 json_decode 不适用于特殊字符。 And no error will be displayed.
并且不会显示错误。 Make sure you remove tab spaces and new lines.
确保删除制表符空格和新行。 Depending on the source you get your data, you might need also: stripslashes(html_entity_decode($string))
根据您获取数据的来源,您可能还需要: stripslashes(html_entity_decode($string))
Works for me:为我工作:
<?php
$sql = <<<EOT
SELECT *
FROM `students`;
EOT;
$string = '{ "query" : "' . str_replace("\t", " ", str_replace("\n", " ", $sql)).'" }';
print_r(json_decode($string));
?>
output:输出:
stdClass Object
(
[query] => SELECT * FROM `students`;
)
I had problem that json_decode
did not work, solution was to change string encoding to utf-8.我遇到了
json_decode
不起作用的问题,解决方案是将字符串编码更改为 utf-8。 This is important in case you have non-latin characters.如果您有非拉丁字符,这很重要。
Interestingly mcrypt_decrypt seem to add control characters other than \0 at the end of the resulting text because of its padding algorithm.有趣的是,由于其填充算法,mcrypt_decrypt 似乎在结果文本的末尾添加了 \0 以外的控制字符。 Therefore instead of
rtrim($jsonData, "\0")
it is recommended to use因此,建议使用而不是
rtrim($jsonData, "\0")
preg_replace( "/\p{Cc}*$/u", "", $data)
on the result $data of mcrypt_decrypt.在 mcrypt_decrypt 的结果 $data 上。 json_decode will work if all trailing control characters are removed.
如果所有尾随控制字符都被删除,json_decode 将起作用。 Pl refer to the comment by Peter Bailey at http://php.net/manual/en/function.mdecrypt-generic.php .
请参考 Peter Bailey 在http://php.net/manual/en/function.mdecrypt-generic.php的评论。
USE THIS CODE使用此代码
<?php
$json = preg_replace('/[[:cntrl:]]/', '', $json_data);
$json_array = json_decode($json, true);
echo json_last_error();
echo json_last_error_msg();
print_r($json_array);
?>
Make sure your JSON is actually valid.确保您的 JSON 确实有效。 For some reason I was convinced that this was valid JSON:
出于某种原因,我确信这是有效的 JSON:
{ type: "block" }
While it is not.虽然不是。 Point being, make sure to validate your string with a linter if you find
json_decode
not te be working.重点是,如果您发现
json_decode
,请确保使用 linter 验证您的字符串。
Try the JSON validator .试试JSON 验证器。
The problem in my case was it used ' not ", so I had to replace it to make it working.我的问题是它使用了'not',所以我不得不更换它以使其工作。
In notepad+ I changed encoding of json file on: "UTF-8 without BOM".在记事本+中,我更改了 json 文件的编码:“UTF-8 without BOM”。 JSON started to work
JSON开始工作
TL;DR Be sure that your JSON not containing comments:) TL;DR确保您的 JSON 不包含评论:)
I've taken a JSON structure from API reference and tested request using Postman.我从 API 参考中获取了 JSON 结构,并使用 Postman 测试了请求。 I've just copy-pasted the JSON and didn't pay attention that there was a comment inside it:
我刚刚复制粘贴了 JSON 并没有注意到里面有评论:
...
"payMethod": {
"type": "PBL" //or "CARD_TOKEN", "INSTALLMENTS"
},
...
Of course after deletion the comment json_decode() started working like a charm:)当然删除后评论 json_decode() 开始像魅力一样工作:)
Use following function:使用以下功能:
If JSON_ERROR_UTF8 occurred :如果发生 JSON_ERROR_UTF8 :
$encoded = json_encode( utf_convert( $responseForJS ) );
Below function is used to encode Array data recursively下面的函数用于对数组数据进行递归编码
/* Use it for json_encode some corrupt UTF-8 chars * useful for = malformed utf-8 characters possibly incorrectly encoded by json_encode */ /* 将它用于 json_encode 一些损坏的 UTF-8 字符 * 用于 = 可能被 json_encode 错误编码的格式错误的 utf-8 字符 */
function utf_convert( $mixed ) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} elseif (is_string($mixed)) {
return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
}
return $mixed;
}
Maybe it helps someone, check in your json string if you have any NULL values, json_decode will not work if a NULL is present as a value .也许它可以帮助某人,如果您有任何 NULL 值,请检查您的 json 字符串,如果 NULL 作为 value 存在,则 json_decode 将不起作用。
This super basic function may help you.这个超级基本的功能可能会对你有所帮助。 I made the NULL in an array just in case I need to add more stuff in the future.
我在数组中设置了 NULL,以防我将来需要添加更多内容。
function jsonValueFix($json){
$json = str_replace( array('NULL'),'""',$json );
return $json;
}
I just used json_decode twice and it worked for me我只使用了 json_decode 两次,它对我有用
$response = json_decode($apiResponse, true);
$response = json_decode($response, true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.