字符串看起来是有效的JSON,但是' json_decode() '返回NULL

时间:2022-07-03 20:29:58

I think I've found where the error lies:

我想我找到了错误所在:

    $convertJSON = file_get_contents("http://www.google.com/ig/calculator?hl=en&q=" . $currencyValue . $currencySelectValue . "%3D%3FUSD", true);
    var_dump($convertJSON);
    $convertArr = json_decode($convertJSON, true);
    var_dump($convertArr);

I do that to debug, and I get this result (I entered 555 and Euros):

我这样做是为了调试,我得到了这个结果(我输入了555和欧元):

string(68) "{lhs: "555 Euros",rhs: "796.64700 U.S. dollars",error: "",icc: true}"
NULL

So it seems that the PHP function to decode the JSON object is doing something wrong somewhere. Any help?

因此,似乎PHP函数解码JSON对象在某些地方做错了。任何帮助吗?

5 个解决方案

#1


3  

The response Google is giving you isn't valid JSON because the labels are not quoted. You'll have to parse it yourself.

谷歌给出的响应不是有效的JSON,因为标签没有被引用。你必须自己去解析它。

$response = '{lhs: "555 Euros",rhs: "796.64700 U.S. dollars",error: "",icc: true';
preg_match('/rhs:\s*"([^"]+)"/', $response, $m);
echo $m[1];

Output:

输出:

796.64700 U.S. dollars

#2


29  

Not a direct response to this question, but an issue I spent a few hours trying to resolve.

不是对这个问题的直接回答,而是我花了几个小时试图解决的问题。

If you are attempting to decode JSON that came from a remote file via CURL, and if that file is in UTF-8 format, the beginning of the file may have the following characters (which breaks json_decode():

如果您正在尝试通过CURL解码来自远程文件的JSON,并且该文件是UTF-8格式,那么该文件的开头可能有以下字符(它破坏了json_decode():



Which you will not see with the naked eye, only via htmlentities(); I have no idea why they are there, I traced this all the way to curl_exec(), thinking that maybe they were being added there. In any case, those little bastards were being added only when file is in UTF-8 format.

只有通过htmlentities();我不知道它们为什么在那里,我一直跟踪到curl_exec(),认为它们可能被添加到那里。无论如何,只有当文件是UTF-8格式时,这些小混蛋才会被添加。

So, assuming you have no control over the encoding of the source file, you can do something like this before passing the string into json_decode():

因此,假设您无法控制源文件的编码,那么在将字符串传递到json_decode()之前,您可以这样做:

$encoding = mb_detect_encoding($json);

if($encoding == 'UTF-8') {
  $json = preg_replace('/[^(\x20-\x7F)]*/','', $json);    
}    

print_r(json_decode($json));

I hope I save somebody some time, it took me a few hours of tracing to figure out that's what was happening.

我希望我能给一些人留点时间,我花了几个小时的时间去追踪,才弄明白这是怎么回事。

#3


1  

strip it of everything but decimal points, commas, and numbers, and give me a result.

除去小数点、逗号和数字之外的所有东西,然后给我一个结果。

Actually you do the exact contrary with your regex. Add a ^ after [: [^ to negate it

实际上,你对你的正则表达式做的恰恰相反。添加一个[:[^ ^之后去否定它

$currencyValue = preg_replace('/([^0-9\.,]+)/', '', $currencyValue);

#4


1  

to make json_encode workable, you have to add double quote to the result string in order to make it in JSON format.

要使json_encode可行,您必须向结果字符串添加双引号,以使其为JSON格式。

I tries the simple code below , and it works fine:

我尝试了下面简单的代码,它工作得很好:

$data = '{lhs: "1 U.S. dollar",rhs: "7.80177256 * dollars",error: "",icc: true}';
$data = str_replace('lhs','"lhs"',$data);
$data = str_replace('rhs','"rhs"',$data);
$data = str_replace('error','"error"',$data);
$data = str_replace('icc','"icc"',$data);
print_r(json_decode($data));

Result:

stdClass Object ( [lhs] => 1 U.S. dollar [rhs] => 7.80177256 * dollars [error] => [icc] => 1 ) 

Now it is in json_decode object!

现在它在json_decode对象中!

#5


0  

Expanding on Matthews answer:

扩大在马修斯回答:

In case for some reason you want all data; (probably not but just in case?)

如果出于某种原因你想要所有的数据;(也许不是,只是以防万一?)

$c='{lhs: "1 British pound",rhs: "1.5358 U.S. dollars",error: "",icc: true}';
$j=json_decode(preg_replace('/({|,)([a-z]+): /','$1"$2": ',$c));
var_dump($j->{'rhs'});

I stumbled across this page before I worked it out so maybe others will too :)

我在构思之前偶然发现了这一页,所以其他人可能也会:

#1


3  

The response Google is giving you isn't valid JSON because the labels are not quoted. You'll have to parse it yourself.

谷歌给出的响应不是有效的JSON,因为标签没有被引用。你必须自己去解析它。

$response = '{lhs: "555 Euros",rhs: "796.64700 U.S. dollars",error: "",icc: true';
preg_match('/rhs:\s*"([^"]+)"/', $response, $m);
echo $m[1];

Output:

输出:

796.64700 U.S. dollars

#2


29  

Not a direct response to this question, but an issue I spent a few hours trying to resolve.

不是对这个问题的直接回答,而是我花了几个小时试图解决的问题。

If you are attempting to decode JSON that came from a remote file via CURL, and if that file is in UTF-8 format, the beginning of the file may have the following characters (which breaks json_decode():

如果您正在尝试通过CURL解码来自远程文件的JSON,并且该文件是UTF-8格式,那么该文件的开头可能有以下字符(它破坏了json_decode():



Which you will not see with the naked eye, only via htmlentities(); I have no idea why they are there, I traced this all the way to curl_exec(), thinking that maybe they were being added there. In any case, those little bastards were being added only when file is in UTF-8 format.

只有通过htmlentities();我不知道它们为什么在那里,我一直跟踪到curl_exec(),认为它们可能被添加到那里。无论如何,只有当文件是UTF-8格式时,这些小混蛋才会被添加。

So, assuming you have no control over the encoding of the source file, you can do something like this before passing the string into json_decode():

因此,假设您无法控制源文件的编码,那么在将字符串传递到json_decode()之前,您可以这样做:

$encoding = mb_detect_encoding($json);

if($encoding == 'UTF-8') {
  $json = preg_replace('/[^(\x20-\x7F)]*/','', $json);    
}    

print_r(json_decode($json));

I hope I save somebody some time, it took me a few hours of tracing to figure out that's what was happening.

我希望我能给一些人留点时间,我花了几个小时的时间去追踪,才弄明白这是怎么回事。

#3


1  

strip it of everything but decimal points, commas, and numbers, and give me a result.

除去小数点、逗号和数字之外的所有东西,然后给我一个结果。

Actually you do the exact contrary with your regex. Add a ^ after [: [^ to negate it

实际上,你对你的正则表达式做的恰恰相反。添加一个[:[^ ^之后去否定它

$currencyValue = preg_replace('/([^0-9\.,]+)/', '', $currencyValue);

#4


1  

to make json_encode workable, you have to add double quote to the result string in order to make it in JSON format.

要使json_encode可行,您必须向结果字符串添加双引号,以使其为JSON格式。

I tries the simple code below , and it works fine:

我尝试了下面简单的代码,它工作得很好:

$data = '{lhs: "1 U.S. dollar",rhs: "7.80177256 * dollars",error: "",icc: true}';
$data = str_replace('lhs','"lhs"',$data);
$data = str_replace('rhs','"rhs"',$data);
$data = str_replace('error','"error"',$data);
$data = str_replace('icc','"icc"',$data);
print_r(json_decode($data));

Result:

stdClass Object ( [lhs] => 1 U.S. dollar [rhs] => 7.80177256 * dollars [error] => [icc] => 1 ) 

Now it is in json_decode object!

现在它在json_decode对象中!

#5


0  

Expanding on Matthews answer:

扩大在马修斯回答:

In case for some reason you want all data; (probably not but just in case?)

如果出于某种原因你想要所有的数据;(也许不是,只是以防万一?)

$c='{lhs: "1 British pound",rhs: "1.5358 U.S. dollars",error: "",icc: true}';
$j=json_decode(preg_replace('/({|,)([a-z]+): /','$1"$2": ',$c));
var_dump($j->{'rhs'});

I stumbled across this page before I worked it out so maybe others will too :)

我在构思之前偶然发现了这一页,所以其他人可能也会: