Why is json_encode adding backslashes? - php

I've been using json_encode for a long time, and I've not had any problems so far.
Now I'm working with a upload script and I try to return some JSON data after file upload.
I have the following code:
print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON
This gives me the following results:
// print_r result
Array
(
[logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
[img_id] => 54
[feedback] => Array
(
[message] => File uploaded
[success] => 1
)
)
// Echo result
{"logo_url":"http:\/\/mysite.com\/uploads\/gallery\/7f\/3b\/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}
Can anyone tell me why json_encode adds slashes?
update
#Quentin said that something is happening between json_encode and .parseJSON and he's right.
Doing a alert(data.toSource()); gives me the dollowing result:
({response:"{\"logo_url\":\"http:\\/\\/storelocator.com\\/wp-content\\/uploads\\/gallery\\/7f\\/3b\\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg\",\"img_id\":\"62\",\"feedback\":{\"message\":\"File uploaded\",\"success\":true}}", status:200})
And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from.
Could it be that the Plupload bind does something to my returned data?
This is my js script:
uploader.bind('FileUploaded', function(up, file, data) {
alert(data.toSource());
$('#' + file.id + " b").html("100%");
});

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).
json_encode($array,JSON_UNESCAPED_SLASHES);

I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.
Here is what was happening. If you do:
$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);
The result is:
["{\"test\":\"2\"}","{\"test\":\"four\"}"]
So, what you actually need to do is:
$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);
And this will return
[{"test":"2"},{"test":"four"}]

Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/" and "\/" are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.

This happens because the JSON format uses ""(Quotes) and anything in between these quotes is useful information (either key or the data).
Suppose your data was : He said "This is how it is done".
Then the actual data should look like "He said \"This is how it is done\".".
This ensures that the \" is treated as "(Quotation mark) and not as JSON formatting. This is called escape character.
This usually happens when one tries to encode an already JSON encoded data, which is a common way I have seen this happen.
Try this
$arr = ['This is a sample','This is also a "sample"'];
echo json_encode($arr);
OUTPUT:
["This is a sample","This is also a \"sample\""]

Make sure your php script has the right header or it will add the slashes
header('Content-Type: application/json');

I had a very similar problem, I had an array ready to be posted. in my post function I had this:
json = JSON.stringfy(json);
the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes. I console.log(json) in every validation and realized that the json was treated as a string instead of an object.
In conclution i shouldn't have assinged json = JSON.stringfy(json) instead i assigned it to another variable.
var aux = JSON.stringfy(json);
This way i keep json as an object, and not a string.

json_encode will always add slashes.
Check some examples on the manual HERE
This is because if there are some characters which needs to escaped then they will create problem.
To use the json please Parse your json to ensure that the slashes are removed
Well whether or not you remove slashesthe json will be parsed without any problem by eval.
<?php
$array = array('url'=>'http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg','id'=>54);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
var x = jQuery.parseJSON('<?php echo json_encode($array);?>');
alert(x);
</script>
This is my code and i m able to parse the JSON.
Check your code May be you are missing something while parsing the JSON

Related

PHP Parse Text into Array

I have an HTML file that I have downloaded using curl and inserted into a string. The HTML file has a lot of content but I am looking to parse a certain section of the document and insert this section into an array. The tricky part of this is that the section that I'm trying to parse is NOT HTML, it's code in JavaScript block:
<!-- script block -->
<script type="text/javascript" src="//external.site.com/76b07.js"></script>
<script>....code.....
"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"},
"235534":{"itemId":"235534","type":"1","image":{"url":"thisotherpic.jpg"}:"summary":"This Other Item"},
</script>
How can I import item information as an array?:
$array = array( "itemId" => "235533", "type" => "0", "image" => "thispic.jpg", "summary" =>"This Item" );
You might use a RegExp to match "....":{....} located between <script> tags. The strings, you're interested in, are JSON variables.
Once you have each json variable in a string, you could try with json_decode()
$json_string = '"235533":{"itemId":"235533","type":"0","image":{"url":"thispic.jpg"}:"summary":"This Item"}';
$json = json_decode($json_string);
$myArray = (array)$json;
Try json_decode function in php
You would first need to figure out how to isolate the data structure using whatever string searching methodologies you can use that are repeatable even when the data changes. It is hard to say what this might be without further context from you about the content around the data structure - i.e. what is the same in all cases, and what varies.
You would then eventually get the data strings and json_decode them as others have suggested.
use regex to match them
preg_match_all('/[0-9]+":{"itemId":"(?P<itemId>[0-9]*)","type":"(?P<type>[0-9]{1})","image":{"url":"(?P<image>.*)"}:"summary":"(?P<summary>.*)}/',$mystring,$elements,PREG_SET_ORDER);
then loop through $elements to get your values
Use explode. For example, something like
$array = explode('","', $string);
that would get close to what you want.
Edit:
This looks like a better fit for you.

Do i need to apply htmlspecialchars / htmlentites on json array?

I wanted to ask that in a php script of mine which I am accessing through an ajax request, I am returning json data ( converted from an array ) as such
echo json_encode($row_array);
I get this data in jquery and display it in a form. Do i need to apply htmlspecialchars / htmlentites before returning the data?
Is do then whats the correct way to do it? The following code gives me an error:
echo htmlentities(json_encode($row_array));
Thanking you
Imran
Do not apply htmlentities in this way. You should walk the array before json encoding it and escape each element, then json encode the array of safe-to-display values. In your usage json is just a transport layer for the array. You are not displaying the json array, just the element data. Don't escape transport layers--it could make the json string invalid.
Context is important.
You don't need to escape the data at all on the server side if it's going into a form input's value if you are using jQuery's val() function to populate it.
Example: http://jsfiddle.net/Y6TWv/1/
var data = '<strong>STRONG TEXT</strong>';
$('input').val(data); // output is escaped
$('p').text(data); // output is escaped
$('p').html(data); ​ // output is not escaped
In addition, if you were to escape the data, don't do it like this:
// escapes the entire json string, not good - quotes will be broken
echo htmlentities(json_encode($row_array));
You would have to escape each item of $row_array first before json encoding it, either with array_map after the array is built, or as you're building the array.
In general, you should prefer htmlspecialchars over htmlentities, but it's not likely you need either one.
I just had a problem with single quotes in a JSON array. Chrome doesn't like single quotes in a JSON response returned via ajax. I escaped each value with htmlspecialchars(, ENT_QUOTES).
$theoptions['MemberList'] = array();
while($row = mssql_fetch_assoc($result)) {
$memberelement = array(
'Display'=> htmlspecialchars($row['FullName'], ENT_QUOTES),
'Value' => $row['ID']);
$theoptions['MemberList'][] = $memberelement;
}
header('Content-Type: application/json');
echo json_encode($theoptions);

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

JSON Encode/decode doesn't work as it should

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

PHP json_encode not returning valid json

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=?

Categories