0
我試圖讓這個URL的請求得到一個比薩餅的定義從谷歌字典API返回的響應... http://www.google.com/dictionary/json?callback=a&client=p&sl=en&tl=en&q=pizza的Json解碼PHP
我的第一反應是這樣的.... 。
a({"query":"pizza","sourceLanguage":"en","targetLanguage":"en","primaries":[{"type":"headword","terms":[{"type":"text","text":"piz·za","language":"en","labels":[{"text":"Noun","title":"Part-of-speech"}]},{"type":"phonetic","text":"/ˈpÄ「tsÉ™/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/pizza.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"pizzas","language":"und","labels":[{"text":"plural"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A dish of Italian origin consisting of a flat, round base of dough baked with a topping of tomato sauce and cheese, typically with added meat or vegetables","language":"en"}]}]}]},200,null)
通過互聯網和similiar問題上stackovrflow拖網捕魚後(如json_decode for Google Dictionary API)我用下面的代碼位試圖解碼之前把它清理乾淨....
$rawdata = preg_replace("/\\\x[0-9a-f]{2}/", "", $rawdata);
$raw = explode("{",$rawdata);
unset($raw[0]);
$rawdata = implode($raw);
$raw = explode("}", $rawdata);
unset($raw[count($raw)-1]);
$rawdata = implode($raw);
$rawdata = "{". $rawdata ."}";
這給了我下面的JSON字符串看...
{"query":"pizza","sourceLanguage":"en","targetLanguage":"en","primaries":["type":"headword","terms":["type":"text","text":"piz·za","language":"en","labels":["text":"Noun","title":"Part-of-speech"],"type":"phonetic","text":"/ˈpÄ「tsÉ™/","language":"und","type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/pizza.mp3","language":"und"],"entries":["type":"related","terms":["type":"text","text":"pizzas","language":"und","labels":["text":"plural"]],"type":"meaning","terms":["type":"text","text":"A dish of Italian origin consisting of a flat, round base of dough baked with a topping of tomato sauce and cheese, typically with added meat or vegetables","language":"en"]]]}
但它仍然不會正確地解碼和我難倒....
我一直在使用這個工具在這裏http://json.parser.online.fr/和它說... SyntaxError:意外的令牌:
我現在認爲,我所有的原始黑客的JSON響應,使可解碼只是讓我的問題變得更糟,並有一個更好的方法來處理原始的迴應。
任何人都可以解釋我的問題嗎?
在此先感謝 :d
在你請求,你問一個 '回調= A'。你得到的結果是jsonp對象。正如你所看到的,json對象位於函數'a'的內部。這個函數'a'是一個回調函數,google用json對象返回給你。例如,打開你的控制檯(在Chrome和Firefox中的F12),並寫在那裏:'function a(json){console.log(json)l};' 然後把響應,你會看到對象 –
我可能錯誤地認爲通過刪除回調部分,剩下的只是json ... – AttikAttak
是的,那是對的。不幸的是,目前您正在移除json主體的必需部分。特別是,如果你有數組[],並且在[{「foo」:「bar」,「foo2」:「bar2」}]中有json對象,那麼你正在剝離{}。你需要修正你的正則表達式,以便它不會使json失效。 – gview