有人可以帮我解决这个问题,我有以下json字符串
string(1223) "YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})"
但我似乎无法随心所欲。基本上我想循环出结果
[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]
很抱歉,我的问题是如何循环甚至打印第一个结果,例如
{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"}
答案 0 :(得分:3)
您的字符串不是JSON,它是JSON-in-Script。注意片段说:
YAHOO.Finance.SymbolSuggest.ssCallback(...)
当浏览器收到上述脚本(实际上是一个javascript代码)时,它将调用YAHOO.Finance.SymbolSuggest.ssCallback
函数,并将JSON数据作为参数传递。
您没有提及是否要访问服务器端或客户端上的JASON数据?它是服务器端(PHP),然后您可以使用正则表达式或字符串替换函数来提取您喜欢的部分。您可以使用json_decode()
函数将结果字符串转换为关联数组。
编辑----
将JSONP转换为JSON的快速而肮脏的黑客行为:
<?php
$text = 'YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"google","Result":[{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GOOG.MX","name": "GOOGLE-A","exch": "MEX","type": "S","exchDisp":"Mexico","typeDisp":"Equity"},{"symbol":"GGQ1.F","name": "GOOGLE-A","exch": "FRA","type": "S","exchDisp":"Frankfurt","typeDisp":"Equity"}]}})';
# //CONVERT JSONP to JSON\\
$text = preg_replace('/.+?({.+}).+/', '$1', $text);
# \\CONVERT JSONP to JSON//
$data = json_decode($text);
var_dump($data);
var_dump($data->ResultSet->Result[0]);
var_dump($data->ResultSet->Result[0]->symbol);
var_dump($data->ResultSet->Result[0]->name);
# etc etc
?>
答案 1 :(得分:1)
您的结果不仅仅是一个JSON字符串,它是一个JSON函数调用前面的JSON字符串。这肯定是一个JSONP电话。
您必须编写YAHOO.Finance.SymbolSuggest.ssCallback(data)
javascript函数并在那里获取Json。检查JSONP查询,如果你想要另一个名字,你应该能够改变这个反向引用函数的名称,它通常是在GET查询中的参数上。
现在你可能直接从PHP调用它而你不在js环境中。因此,您必须在PHP代码中编写一些内容,以删除YAHOO.Finance.SymbolSuggest.ssCallback(
部分以及之前的)
将其解析为JSON数据..