我正在尝试通过以下代码对此json数据进行解码,但无法正常工作。
$data = 'VA_OnQueryData({"name":"John","id":"354902332592"});';
return json_decode($data);
答案 0 :(得分:10)
摆脱URL中的callback
参数。代替这个:
https://api.vinaudit.com/query.php?key=VA_MAIN&callback=VA_OnQueryData&vin=1C6RR6LT3HS847897
使用此:
https://api.vinaudit.com/query.php?key=VA_MAIN&vin=1C6RR6LT3HS847897
然后,您将获得真正有用的JSON。
您使用的方法是JSON-P,过去曾通过发送可执行JavaScript来解决跨域问题。感谢CORS,此方法不再需要客户端使用,而服务器端也不再需要。
此外,请返回使用此API的人,并告诉他们他们使用了错误的Content-Type
响应标头。他们正在发送text/html
...应该是application/json
。 (参考:https://stackoverflow.com/a/477819/362536)
答案 1 :(得分:1)
您好,您尝试json_decode的是无效的json。
如果必须以这种方式使用它,则需要先按以下步骤对其进行清洁:
$data = 'VA_OnQueryData({"vin":"1C6RR6LT3HS847897","id":"697015470432","attributes":{"VIN":"1C6RR6LT3HS847897","Year":"2017","Make":"Ram","Model":"1500","Trim":"Lone Star","Made In":"United States","Style":"Crew Cab Pickup (4-Door)","Engine":"5.7L V8 OHV 16V"},"success":true,"error":""});';
preg_match('/{.*}/', $data, $cleaned);
return json_decode($cleaned[0]);
此输出为:
stdClass Object
(
[vin] => 1C6RR6LT3HS847897
[id] => 697015470432
[attributes] => stdClass Object
(
[VIN] => 1C6RR6LT3HS847897
[Year] => 2017
[Make] => Ram
[Model] => 1500
[Trim] => Lone Star
[Made In] => United States
[Style] => Crew Cab Pickup (4-Door)
[Engine] => 5.7L V8 OHV 16V
)
[success] => 1
[error] =>
)
答案 2 :(得分:0)
它不工作,因为它不是json。尝试以下方法:
$data = '{"name":"John","id":"354902332592"}';
return json_decode($data);