【问题标题】:What to do with JSON text output?如何处理 JSON 文本输出?
【发布时间】:2015-04-08 21:57:13
【问题描述】:

我是第一次使用 API。使用 cURL,我可以从 API 获取令牌并使用它来获取 JSON 格式文本的响应。这是我的代码:

<?php
$host = 'HOST';
$username = 'USERNAME';
$password = 'PASSWORD';
$payloadName = 'grant_type=client_credentials';
$process = curl_init($host);
curl_setopt($process, CURLOPT_HTTPHEADER, array('application/x-www-form-urlencoded'));
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($process, CURLOPT_SSL_VERIFYHOST,  2);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_POST, 1);
curl_setopt($process, CURLOPT_POSTFIELDS, $payloadName);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($process);
$str = ''.$return.'';
$start  = strpos($str, '{');
$end    = strpos($str, '}', $start - 1);
$length = $end - $start;
$json = substr($str, $start - 1, $length + 2);


$results = json_decode($json, true);
$token = $results['access_token'];
$type = $results['token_type'];


$curl = curl_init( "API URL?fields=title,author" );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $token) );
$return2 = curl_exec( $curl );

?>

我的问题是,为令牌解码 JSON 似乎工作正常,但 $return2 的值只是“1”或“true”,所以如果我使用相同的方法,就没有什么可解析的了。

这是输出文本结果,例如:

{"id":xxxxxx,"title":"War dogs","author":"Bear, Greg, 1951-"}

到网页,那么我如何将输出的内容捕获到我可以使用的变量中,无论是服务器端还是客户端?

【问题讨论】:

  • 使用JSON.parse()
  • @dave - 那是红宝石,不是 PHP ;-)
  • @dbinns66 嗯,不,那是 JavaScript
  • @dave - LOL 在 ruby​​ 中工作得很好 ;-) 我坐得更正了...

标签: php jquery json rest


【解决方案1】:

JSON 是一种原生的 Javascript 表示法。事实上,它代表“JavaScript Object Notation”。例如,

var jsonobj = {"id":123456,"title":"War dogs","author":"Bear, Greg, 1951-"};

是有效的 JS。它会生成一个您可以使用的对象。

alert(jsonobj.title); //alerts "War Dogs"

根据您的示例,我不确定如何获得变量集。如果变量 $json 在 PHP 文件的 HTML 部分中可供您使用,则可以在 &lt;script&gt; 部分中执行以下操作:

var jsonobj = <?php echo $json; ?>;

【讨论】:

  • 作为旁注,最好将结果 json_decode 并在使用 json_encode 输出时再次转义。这将解决因服务响应错误而引起的任何潜在安全问题。
猜你喜欢
  • 1970-01-01
  • 2022-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多