如何修复代码以打印jSON语法? [英] How can I fix my code to print a jSON syntax?

查看:129
本文介绍了如何修复代码以打印jSON语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取jSON外观相似的页面的内容并打印所有值,如下面的代码所示.

I am trying to get the content of a jSON look alike page and print all the values, as you can see in my code below.

更新后的代码

<?php
$json = file_get_contents('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&year=2007&make=mini');

$vres = array('?({"Trims":' , '});');
$allakse = array("" , "");
$json = str_replace($vres, $allakse, $json);


echo $json;


$cars = json_decode($json, true);

foreach ($cars[0] as $value)
{
    echo $value, "<br>";
}

这是文件的外观.

?({
Trims: [
{
   "model_id":"15155"
  ,"model_make_id":"ford"
  ,"model_name":"Taurus"
  ,"model_trim":""
  ,"model_year":"2000"
  ,...(all available model fields are included)
 },
{
   "model_id":"15073"
  ,"model_make_id":"ford"
  ,"model_name":"Taurus"
  ,"model_trim":"3.0"
  ,"model_year":"2000"
  ,...(all available model fields are included)
  },
  {etc...}
]});

即使我替换了一些字符以使其在开头和结尾看起来都像jSON语法,我也无法使其正常工作.我在做什么错了?

Even that I replaced some characters to make it look like a jSON syntax at the begining and end, I can't get it to work. What am I doing wrong?

推荐答案

响应已损坏JSON-P,而不是JSON.

The response is broken JSON-P, not JSON.

JSON-P包含一个函数调用(对您在URL中指定的函数名称(在本例中为?)),该数据具有通过第一个参数传递的数据.

JSON-P consists of a function call (to a function name that you specify in the URL (? in this case)) with data passed via the first argument.

在JSON-P中,该数据应为JSON.在这种情况下,不是.这是一个JavaScript对象文字,不符合与JSON规范匹配的子集. (特别是,您将属性名称表示为标识符,而不是字符串文字).

In JSON-P, that data is supposed to be JSON. In this case, it isn't. It is a JavaScript object literal that doesn't conform to the subset that matches the JSON spec. (Specifically, you have property names expressed as identifiers instead of string literals).

您可以使用 JSON验证器来识别JSON响应中的错误并尝试清除它们(可能使用一些邪恶的正则表达式).

You could use a JSON validator to identify the errors in the JSON response and try to clean them up (probably using some unholy set of regular expressions).

或者,您可以考虑运行JavaScript引擎(例如Node.js或Rhino),定义一个函数,该函数将第一个参数传递给JSON.stringify(),然后打印结果(然后将其捕获回PHP变量中) ).

Alternatively, you could look at running a JavaScript engine (such as Node.js or Rhino), defining a function that passes the first argument to JSON.stringify(), then prints the result (and then capturing that back into a PHP variable).

更新:

我已经查看了您提供的URL.输出与问题中的数据不匹配. JSON确实有效,并且没有代码显示的问题.

I've looked at the URL you provided. The output does not match the data in the question. The JSON does appear to be valid and without the problems your code shows it to have.

只需停止要求callback=?来获取JSON而不是JSON-P.然后,您无需剥离JSON-P包装器.

Just stop asking for callback=? to get JSON instead of JSON-P. Then you don't need to strip off the JSON-P wrapper.

这篇关于如何修复代码以打印jSON语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆