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'};
Related
I need to use a customer's API for loading JSON which only contains something like:
{"html" : "foo"}
The API is being used from other services so I'm pretty sure it's valid.
However, when trying to decode it using json_decode i'm always getting an empty string which means it's not valid. I found out i need to "fix" the JSON-String by replacing:
$json = str_replace("\\>", "\\\\>", $json); // \> = invalid json
It works mainly on each request but not on certain others but it's very tricky to debug and i can't imagine that replacing is the proper method.
How would i do it the easy way for converting the json string into a valid one?
thanks
Ok i could find out what's wrong:
The HTML contains backslashes in the closing tags, for example <br\>
You need to replace them like this:
$json = str_replace("\\>", "\\\\>", $json);
and json_decode will work
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 am preparing and sending a JSON string from my PHP file to my Javascript function like this:
$json = array();
$json['slice'] = false;
$json['G500'] = false;
$json['KG1'] = false;
$encoded = json_encode($json);
die($encoded);
However, in my JS function, if I do this, it is unable to decode the JSON object:
var d = req.responseText;
var jsonObject = eval(d);
The only way, I can get it to eval the JSON object is by adding parentheses manually
jsonObject = eval("(" + d + ")");
I have the same problem going in reverse as well. Sending a JSON object to PHP and trying to decode it there fails. I believe I would need to remove the parentheses in my PHP script before attempting to decode.
Why is this happening? Is there something I can do to work around this incompatibility?
EDIT:
PHP to JS is now working if I use JSON.parse. I'm still having trouble the other way around.
This is how I'm sending the data to the PHP:
var JSONstring =
{
"Product": document.getElementById('item').value,
"Size": document.getElementById('size').value,
"Quantity": document.getElementById('quantity').value
};
url = "maintainOrder.php?json=" + JSON.stringify(JSONstring);
req.open("GET", url, true);
However, the PHP script is unable to decode it.
$newItem = json_decode($_GET['json']);
array_push($_SESSION['order'],$newItem);
Your Javascript
eval has an issue with leading { characters, because of an ambiguity with block scope.
Using the parentheses to force the input to be parsed as an expression is a solution, but you should avoid eval entirely and use a proper JSON decoding function.
Your PHP
We'd need to see the data that you send to your PHP script to know why it won't parse. In general, as long as JSONLint accepts your JSON, so will PHP's json_decode. So give that a go.
For the php to javascript issue refer to the Tomalak Geret'kal answer.
For the javascript to php maybe I have the solution:
If you want an associative array in php then you have to pass assoc parameter as true into json_decode (default to false)
Example:
$array = json_decode($jsonString, true);
I was bitten a couple of times by this: by default json_decode try to create an object if it receive a javascript object (it make perfect sense if you think of) and you have to force it to render an associative array if you need this behaviour
I think you need to do some string processing, all you need to do is echo and see the exact format of your JSON string and make sure it conforms to the standard format, then use string processing both on the server and client sides to achieve the desired effect
Are you sure php is not adding slashes to the json text?, try saving the json text in a file in the server side to verify
I am running a Debian box with PHP v5.2.17. I am trying to get around the cross-domain issue with an XML file and am using this got to fetch any xml and return json:
<?php
header('content-type: application/json; charset=utf-8');
if( strlen($_GET["feed"]) >= 13 ) {
$xml = file_get_contents(urldecode($_GET["feed"]));
if($xml) {
$data = #simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($data);
echo isset($_GET["callback"]) ? "{$_GET[’callback’]}($json)" : $json;
}
}
?>
The problem is, its not returning valid json to jquery.. The start character is "(" and the end is ")" where jquery wants "[" as the start and "]" as the end. I've taken the output and used several online validation tools to check it..
Is there a way I can change these characters prior to sending back or pass json_encode options?
You could change json_encode($data) to json_encode(array($data)) if it expects an array (like you're saying):
$json = json_encode(array($data));
EDIT: Also, I believe the SimpleXml call will result in a bunch of SimpleXmlElements, perhaps json_encode then thinks it should be objects, instead of arrays? Perhaps casting to an array will yield the correct results.
You cannot json_encode() SimpleXMLElements (that's the type that is returned by simplexml_load_string(). You have to convert the data from the XML file into some native PHP type (most likely an array).
SORRY that's wrong. json_encode() can in fact encode SimpleXMLElements (at least on my PHP version 5.3.4). So if your client-side code expects an array you must wrap your $data in an array:
$json = json_encode(array($data));
We can use json_encode() function most probably on array. so you first take XML content into PHP array and then apply json_encode().I think this will solve your problem..
It seems that you are sending an empty callback parameter or something, but the callback parameter in jQuery must look exactly like this: callback=?
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..