JSON Encode/decode doesn't work as it should - php

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

Related

Decode json With PHP not working

I am trying to decode json with PHP but dont know where am i wrong. Here is my code
$rr ='var modelsGlobal = [{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}{"value":"FAFW3801LW","productdetailurl":"/Washers-Dryers/Washers/Front-Load/FAFW3801LW/"}]';
$json = json_decode($rr, true);
foreach($json['modelsGlobal'] as $json){
$prod_id = $json["value"];
}
Please help
You are trying to decode (broken) JavaScript, not JSON.
JSON wouldn't include var modelsGlobal = and array members need a , between them.
Run your data through a linter.
After you fix the errors which are preventing the parsing, the JSON doesn't start with an object with a modelsGlobal, so loop over the array in $json directly.
Your JSON is incorrect. It is not JSON but JavaScript and it lacks a comma to separate the two objects of the array.
If you use PHP 5.3+ use json_last_error to check errors with json_encode/json_decode.

JSON - proper way to decode string in JavaScript

I'm wondering what would be the best way to decode JSON string inside Javascript code.
I want my json string to be embeded inside my JS, like this:
var params = dojo.fromJson('<?=json_encode($this->params); ?>');
dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side.
It seems that json encoder ignores ' chars and only converts " to \". So when one of my variables inside $this->params contains a ' character there is a Javascript error.
For example:
var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');
What is the best way to approach this ?
Thanks for help.
Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead.
var params = <?=json_encode($this->params); ?>;
PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data.

Simple JSON request in PHP

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'};

JSON concept with javascript & PHP

I need someone to shed some light on this subject.
When a person do an AJAX call, that call a php script which echo out json_encode stuff, so that the javascript can mess around with it. Note: Assuming we set the header to json in the php script.
The data that the javascript receive from the php script, do we have to parse it using eval or json's library? Edit: Is it because it treats the data recieved from the php file as text and not as javascript?
Can we use the javascript dot-notation on the data that the php script returned? Or does this data have to some how be converted to a javascript object before we can use dot-notation?
Thank you in advance.
JSON is merely a string, which happens to conform to Javascript's syntax for objects (hence the abbreviation: JavaScript Object Notation.)
To convert it to a Javascript object, you can use the eval function, but for greater security, it's recommended to use the JSON object included in modern browsers, or a function provided by your Javascript library of choice:
var json = '{"thing":1, "thang":"two"}';
var obj1 = eval('('+json+')'); // easier, less secure
var obj2 = JSON.parse(json); // secure, but doesn't work everywhere
var obj3 = jQuery.parseJSON(json); // secure, works everywhere
Many libraries will also handle the conversion for you as part of the Ajax request. Here's how jQuery does it:
jQuery.get('http://domain.com/path/to/request', function(obj)
{
// string is automatically converted to an object,
// usable as array or with dot notation
alert(obj.thing);
alert(obj['thang']);
},
'json'); // indicates that we are requesting json and not html
You can always use a library like jQuery, Mootools, Prototype, etc. for the decoding JSON text to Javascript variables..
JSON is something like serialize from PHP :) It's a way to transform string to object and back :)

JSON from Javascript not decoding in PHP

I've been going bananas trying to get some data from Javascript on one page to post to a php file asynchronously. I'm not even attempting to do anything with the data, just a var_dump to spit back out from the ajax call. NULL over and over again.
I've checked the JSON with JSONLint and it validates just fine. I'm getting my JSON from JSON.stringify - Firebug tells me I'm getting the following:
{"items":[["sa1074","1060"],["sa1075","1061"]]}
I've tried php://input, as well as json_decode_nice from the PHP manual comments about the function, and I've tried using utf8_encode - is there something wrong with my JSON?
EDIT: Derpity dee probably should have planned this post a bit more haha. Here's my PHP (using a suggestion from PHP manual comments)
function json_decode_nice($json, $assoc = FALSE){
$json = str_replace(array("\n","\r"),"",$json);
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
return json_decode($json,$assoc);
}
if (isset($_POST['build'])){
$kit = file_get_contents('php://input');
var_dump(json_decode_nice($kit));
}
And the JS used to create it:
var jsonKit = JSON.stringify(kit);
$.post("kits.php?", {"build" : jsonKit},
function(data) {
$("#kitItems").html(data);
});
Also: Our host is on PHP 5.2 - I found this out when I uploaded a perfectly good redbean class only to have it explode. Had to re-implement with legacy redbean. Our host is busted.
SOLVED: Thanks to all who commented. Didn't think to check $_POST to see what was coming in. Quotes were being escaped with slashes in the $_POST and json_decode was choking on it. Adding this line before decoding solved the problem. Also forgot to set true to return an associative array. Thanks!
$kit = str_replace('\\', '', $kit);
Without seeing code - I'm just guessing here ... are you using a true assoc variable in your json_decode()?
<?php json_decode($jsonString, true); ?>
That had me stumped on a decode for quite some time my first time trying to decode something,

Categories