I have a set of data that looks like this when using print_r($var):
cbfunc({"query":{"count":"12","created":"2010-06-11T01:20:19Z","lang":"en-US"},"results":["\n 238.l.739089.t.4<\/team_key>\n 4<\/team_id>\n CHEE-HOO!!!<\/name>"]});
It looks like JSON to me, so I've tried to use json_decode but can't get it right. My goal is to print the xml data found in "results".
Any helpful pointers would be greatly appreciated.
It looks like it is wrapped in a callback cbfunc. so you need to strip that out before you can run json_decode on it.
try
$decode_this = substr($var, 6, -1);
You don't show the end of the responseText but the snippet above should give you everything between the start of the callback 'cbfunc(' and the last char, exclusive. You may have to change it to -2 if there is also a ; etc.
Thanks to ZZ Coder's response, I figured out the solution.
According to a comment on the json function at PHP. The JSONP needs to be converted to JSON (without padding) via a handy preg_replace...
$var=preg_replace('/.+?({.+}).+/','$1',$var);
Then, the JSON can be parsed to print the results data:
$obj = json_decode($var, true);
print $obj["results"][0];
Related
For example i have json strings like this ( from the first place ). And It's not formatted.
{"data":[{"id":"14","memo_kondisi":"Kekurangan
pekerjaan","total_row":"5","nilai_temuan":"1.000.000","data_sebab":[{"id":"15","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"25","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"26","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"31","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]},{"id":"16","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[{"id":"34","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"},{"id":"35","id_rekomendasi":"10","id_sub_rekomendasi":"","id_s_sub_rekomendasi":"","nilai_rekomendasi":"0"}]}]},{"id":"15","memo_kondisi":"Kekurangan
pekerjaan","total_row":"2","nilai_temuan":"1.000.000","data_sebab":[{"id":"5","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"10","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]},{"id":"16","memo_kondisi":"","total_row":"2","nilai_temuan":"0","data_sebab":[{"id":"9","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]},{"id":"12","id_sebab":"","id_sub_sebab":"","memo_sebab":"coba","data_rekomendasi":[]}]}]}
I see some similar question that you have to use json_decode and i have to encode again and using json_encode($json,JSON_PRETTY_PRINT)
Is there a way for make json readable without decode the JSON first and encode it again in PHP ?
Note : I expect the result is still in JSON
Not really. Using someone else's parser lib won't make any difference, as they'll call json_decode() too.
You could create a little function that you could call:
function prettify($json)
{
$array = json_decode($json, true);
$json = json_encode($array, JSON_PRETTY_PRINT);
return $json;
}
Then echo prettify($jsonString); would be easier than constantly decoding and re-encoding. See here https://3v4l.org/CcJlf
Only a parser can understand the JSON, so you can either do what you proposed or write your own parser. If you have access to the origin of the JSON, make it pretty in the first place.
I have extracted data from another website which is in JSON format - here is what I extracted: http://sub7legends.net/crawler.php
I need to get the value of kills and deaths from this.
I tried json_decode() in php of this data but when I var_dump() the result it just says "NULL".
What can I do to extract the required data?
The link doesn't work for me. But if you have a normal json just like this one:
{"kills": "5", "deaths": "3"}
Then the json_decode() method should work.
Here would be a sample code snippet:
$json_you_got_from_the_server = '{"kills": "5", "deaths": "3"}';
$result = json_decode($json_you_got_from_the_server);
$kills = $result->kills;
$deaths = $result->deaths;
echo "You have ".$kills." kills and ".$deaths." deaths.";
I haven't tried it, but it should work. If it doesn't, then please comment and I will try something else.
the current json contents are not valid, try validating it first. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
That json in the link you have pasted has no proper ending scroll to the end and you will see. If this is the same thing that you wanted to parse then it will always return null.
i need to remove () backslash in my string when using echo json_encode()?
my example..
$song_url = 116e9155e0afc11555cf33dc9c9bd25d.mp3
$resmsg[] = array("Song_name"=>"$song_name","Song_URL"=>"http://www.kbmusique.com/songs/$song_url");
echo json_encode($resmsg);
my output is
[{"Song_name":"djigh araouioui","Song_URL":"http:\/\/www.kbmusique.com\/songs\/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
but i need as
[{"Song_name":"djigh araouioui","Song_URL":"http://www.kbmusique.com/songs/116e9155e0afc11555cf33dc9c9bd25d.mp3"}]
Is there a way to solve this? Thank you.
Your comment indicates that you just need to get a copy/pastable URL for testing.
Just parse the JSON and extract the piece of data you need from it. i.e. If you want a text representation of something, then convert the JSON to text, don't try to hack the JSON into a specific form.
You could do this in PHP with json_decode, in a browser with JSON.parse(), or just use a tool such as the Chrome JSONView extension.
I have the following json
country_code({"latitude":"45.9390","longitude":"24.9811","zoom":6,"address":{"city":"-","country":"Romania","country_code":"RO","region":"-"}})
and i want just the country_code, how do i parse it?
I have this code
<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = file_get_contents($json);
var_dump(json_decode($jsonfile));
?>
and it returns NULL, why?
Thanks.
<?php
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
var_dump(json_decode($json));
?>
You just need json not jsonp.
You can also try using json_decode($json, true) if you want to return the array.
you're requesting jsonp with http://api.wipmania.com/jsonp?callback=jsonpCallback, which returns a function containing JSON like:
jsonpCallback({"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}})
and not JSON itself. change your URL to http://api.wipmania.com/json to return pure JSON like:
{"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}}
notice the second chunk of code doesn't wrap the json in the jsonpCallback() function.
The website doesn't return pure JSON, but wrapped JSON. This is meant to be included as a script and will call a callback function. If you want to use it, you first need to remove the function call (the part until the first paranthesis and the paranthesis at the end).
If your server implements JSONP, it will assume the callback parameter to be a JSONP signal and the result will be similar to a JavaScript function, like
jsonpCallback("{yada: 'yada yada'}")
And then, json_decode won't be able to parse jsonpCallback("{yada: 'yada yada'}") as a valid JSON string
If country_code( along with closing parenthesis are include in your json, remove them.
This is not a valid json syntax: json
You are being returned JSONP, not JSON. JSONP is for cross-domain-requests in JavaScript. You don't need to use it when using PHP because you aren't affected by cross-domain-policies.
Since you are getting a string from the file_get_contents() function you can do a replacement of the country_code( text (this is the JSONP specific part of the response):
<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = substr(file_get_contents($json)), 13, -1);
var_dump(json_decode($jsonfile));
?>
Note
This works but JKirchartz's solution looks better, just request the correct data rather than messing around with the incorrect data.
Obviously in this situation, using the correct URL to access the API will return pure jSON.
"http://api.wipmania.com/json"
A lot of people are providing an alternative to the API in use, rather than answering the OP's question, so here is a solution for those looking for a way of handling jSONp in PHP.
First, the API allows you to specify a callback method, so you can either use Jasper's method of getting the jSON sub string, or you can give a callback method of json_decode, and modify the result to use with a call to eval. This is my alternative to Jasper's code example since I don't like to be a copy cat:
$json = "http://api.wipmania.com/jsonp?callback=json_decode";
$jsonfile eval(str_replace("(", "('", str_replace(")", "')", file_get_contents($json)))));
var_dump($jsonfile);
Admittedly this seems a little longer, more insecure, and not as clear to read as Jasper's code:
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = substr(file_get_contents($json)), 13, -1);
var_dump(json_decode($jsonfile));
Then the jSON "address":{"city":"-","country":"Romania","country_code":"RO","region":"-"} tells us to access the country_code like so:
$jsonfile->{'address'}->{'country_code'};
Could some one please help me out on this I have the following json string
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"}]}})"
But I cannot seem to get anywhere with it. Basically I want to just loop out the the results which are
[{"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"}]
Sorry my question is how can I loop or even print the first result for example
{"symbol":"GOOG","name": "Google Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"}
Your string is not JSON, it is JSON-in-Script. Notice the fragment that says:
YAHOO.Finance.SymbolSuggest.ssCallback(...)
When a browser receives the above mentioned script (actually a javascript code) it will call the YAHOO.Finance.SymbolSuggest.ssCallback function, passing the JSON data as the argument.
You did not mention if you want to access the JASON data on the server side or client? It its server side (PHP) then you can use regular expressions or string replacement functions to extract the portion you like. The you can use json_decode() function to convert the resulting string into an associative array.
Edit ----
A quick and dirty hack for converting JSONP to 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
?>
Your result is not just a JSON string, it's a JSON string prepended by a call to a JSON function. This is quite certainly a JSONP call.
You must write the YAHOO.Finance.SymbolSuggest.ssCallback(data) javascript function and get the Json there. Check the JSONP query, you should be able to alter the name of this backreference function if you want another name, it's usually on of the parameter in the GET query.
Now you are maybe calling it directly from PHP and you are not in js envirronment. so you must write something in your PHP code to remove the YAHOO.Finance.SymbolSuggest.ssCallback( part and the ) at the end before parsing it as JSON data..