json_encode remove quotes from keys? - php

If I use json_encode() on an array like this:
return json_encode(array( 'foo' => 'bar'));
The return is:
{'foo' : 'bar'}
The key is passed as a literal, and that is tripping up my script. What I really need is:
{ foo : 'bar' }
Does json_encode do that or do I have to strip the quotes out myself with some ugly regex?

When I test this portion of code :
echo json_encode(array( 'foo' => 'bar'));
die;
I get :
{"foo":"bar"}
Which is valid JSON.
(Note these are double-quotes, and not simple-quotes as you posted)
The ouput you are asking for :
{ foo : 'bar' }
is valid Javascript, but is not valid JSON -- so json_encode will not return that.
See json.org for the specification of the JSON format -- which is a subset of Javascript, and not Javascript itself.
Instead of "stripping the quotes out myself with some ugly regex", you should adapt your code, so it accepts valid JSON : this is way better, in my opinion.

No, json_encode will not do this for you. The json specification specifcally requires that keys be quoted strings. This is done to ensure that keys which are javascript reserved words won't break the data object.

If you want to convert your JSON to print a javascript object (that was my case) you can use ugly regex like this:
$myJsonString = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $myJsonString);
Source: https://hdtuto.com/article/php-how-to-remove-double-quotes-from-json-array-keys

How is it tripping up your script?
And per the JSON specification, key names are supposed to be strings. The 2nd snippet you posted is not valid JSON.

Thanks, everyone. I did not know that about the JSON spec. The issue was in fact with my script because I had not set the datatype of my $.ajax() function to "json"
What I learned today -- JSON and Javascript are not the same thing!

Related

Json_encode for .post?

can anyone explain the purpose of json_encode when doing a .post query.
This is what i often see in other's coding.
.post php script
...
...
echo json_encode($a);
I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?
.post php script
...
...
$a = array("foo", "bar", "hallo", "world");
$string=implode(',',$a) in my php script
return $string;
javascript
$.post('$url',function(data){
data_arr=data.split(',');
//After which just get the values in the array
alert(data_arr[0]); //ALERTS 'foo'
alert(data_arr[1]); //ALERTS 'bar'
});
If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.
Perhaps its also due to my inept knowledge of JSON as well.
Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.
Thanks.
Using json_encode ensures that your data is always valid.
It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.
Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.
First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.
For example:
If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)
Example code using commas:
<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>
The javascript that receives the string
$.post(url,{},function(data){
var values = data.split(',')
$("#name").text(values[0]);
$("#surname").text(values[1]);
$("#interests").text(values[2]);
});
So it makes sense right? But wouldn't it more sense to do this instead:
<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>
And the javascript:
$.post(url,{},function(data){
for(index in data) {
$("#"+index).text(data[index]);
}
//or
$("#name").text(data.name);
$("#surname").text(data.surname);
$("#interests").text(data.interests);
});
The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.
Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.
Also JSON is now a standard. Everyone uses it which means that it's not for no reason.
In other words - JSON data makes more sense.

Hardcode JSON Array in PHP

I have two variables from two different SQL queries that I want to put in to one JSON Array (i.e $hometown and $topcat). I am trying to hardcode it but not sure how it's suppose to look.
print(json_encode('{"hometown":"' . $hometown .'", "category":"'. $topcat .'"}'));
My output is this:
{\"hometown\":\"Seattle, WA\", \"category\":\"Movies\"}"
Not sure where the slashes are coming from (I suppose I can to do stripslashes?) and it seems I need to add '[' and ']' as well? What is the proper formatting for this?
json_encode() takes your array or object, it doesn't accept strings that are already JSON encoded. It can be done like this:
print json_encode(array('hometown' => $hometown, 'category' => $topcat));
Outputs
{"hometown":"Seattle, WA","category":"Movies"}
That string already looks like JSON; why are you trying to encode it again?
Not sure where the slashes are coming from
Because that code encodes a string that contains double-quotes, which must be escaped in JSON.
Unsafe, and dumb, but easy solution:
print('{"hometown":"' . $hometown .'", "category":"'. $topcat .'"}');
Better solution:
print(json_encode(array(
'hometown' => $hometown,
'category' => $topcat,
)));
The string is already formatted as a JSON object, encoding is what is adding the slashes. The json_encode() function is made to convert arrays to JSON objects not strings also whats with the print(), print() is deprecated and echo() should be used.
Here is your solution:
echo '{"hometown":"'.$hometown.'", "category":"'.$topcat.'"}';

PHP - how to create object or associative array from a JSON string

I need to create an array or an object from a given string. String is received in a post and is a serialized js object.
I get a string like:
{'id': n, 'propery 1': 'something', 'propery 2': 'something else', etc.}
or
{'whatever': bla bla, etc.} (without the id part).
I need to transform that in a php object or array or... something usable.
I'm aware that I could extract the substrings or explode(': ', $string) but I not really efficient. The received strings are really close to json format (with only 1 or 2 exceptions that I can treat separately).
Use json_decode($string) ==> php Object (or array if you force with a param).
Use json_encode($array) ==> string
You can use JSON decode method in PHP: http://php.net/manual/en/function.json-decode.php
Here's what you need json_decode : http://php.net/manual/en/function.json-decode.php
you can use json_encode(). http://in.php.net/manual/en/function.json-encode.php
Looks like JSON. You can use json_decode(): http://php.net/manual/en/function.json-decode.php

exported json as string (not array)

Some have see that code :
<?php
echo stripslashes(json_encode(glob("photos-".$_GET["folder"].'/*.jpg')));
?>
it echo a really nice perfect string like that :
["photos-animaux/ani-01.jpg","photos-animaux/ani-02.jpg","photos-animaux/ani-02b.jpg","photos-animaux/ani-03.jpg","photos-animaux/ani-04.jpg","photos-animaux/ani-05.jpg","photos-animaux/ani-06.jpg","photos-animaux/ani-07.jpg","photos-animaux/ani-08.jpg","photos-animaux/ani-09.jpg","photos-animaux/ani-10.jpg","photos-animaux/ani-11.jpg","photos-animaux/ani-12.jpg","photos-animaux/ani-13.jpg","photos-animaux/ani-14.jpg"]
With json encode it shoul send a array so variable[0] should = to photos-animaux/ani-01.jpg
NOW it is only the fisrt caracter of the string..
how a array get converted to string, and how in javascipt to convert string to array to be able to get value [0] [1] etc..
the question is WHEN or WHY the perfect array get converted to string anyway ?
Using JSON.parse(), from the library available here, is preferable to using eval() since this only reads JSON strings and hence avoids the inherant security risks associated with eval().
In order to parse a JSON-encoded string into actual javascript objects, you need to eval() the data returned in order for javascript to execute against the data:
var data = eval(json_string)
Keep in mind that you should only ever run eval on a string when you trust the source and are sure that there is no possibility of a script injection attack, since javascript will run everything present in the string.
Use one of the JSON libraries listed at the bottom of http://json.org/
WHEN or WHY
If I understood correctly, the answer to both is json_encode(): check out the documentation. Converting a variable to a string (often called serialization or flattening) is a quite common operation.

Problem with json_encode()

i have an simple array:
array
0 => string 'Kum' (length=3)
1 => string 'Kumpel' (length=6)
when I encode the array using json_encode(), i get following:
["Kum","Kumpel"]
My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?
"{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.
$array = array("a","b","c");
json_encode($array); // ["a","b","c"]
json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.
Note: according to PHP manual the options parameters are only available from PHP 5.3.
For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.
As Gumbo said, on the JS-side it won't matter. To force PHP into it, try this:
$a = new stdClass();
$a->{0} = "Kum";
$a->{1} = "Kumpel";
echo json_encode($a);
Not that usable, I'd stick with the array notation.
Just cast as an object and it will work fine...the JSON_FORCE_OBJECT parameter does exactly the same thing.
json_encode((object)$array);
Don't forget to convert it back into a php array so you can access its values in php:
$array = (object)$array;
$array = (array)$array;
json_encode($array);
Since you’re having a PHP array with just numeric keys, there is no need to use a JavaScript object. But if you need one, try Maiku Mori’s suggestion.
I personally think this is a bug that needs to be fixed in PHP. JSON_FORCE_OBJECT is absolutely not an answer. If you try to do any sort of generic programming you get tripped up constantly. For example, the following is valid PHP:
array("0" => array(0,1,2,3), "1" => array(4,5,6,7));
And should be converted to
{"0": [0,1,2,3], "1": [4,5,6,7]}
Yet PHP expects me to either accept
[[0,1,2,3],[4,5,6,7]]
or
{"0":{"0":1,"1":1,"2":2,"3":3},"1":{"0":4,"1":5,"2":6,"3":7}}
Neither of which are right at all. How can I possibly decode an object like that? What possible reason is there to ever change something that is clearly using strings as indexes? It's like PHP was trying to be clever to help out idiotic people who can't differentiate strings from ints, but in the process messed up anyone legitimately using strings as indexes, regardless of what the value COULD be turned into.

Categories