JSON to Javascript object literal notation? - php

The methods of the dynamic Google Graph API want Javascript object literals as their argument, but I only have the data as JSON. What do I do? Is there any way that I could convert my JSON to an object literal?
The format they want is here:
http://code.google.com/intl/sv-SE/apis/chart/interactive/docs/reference.html#DataTable
I PHP, and also jQuery front end. I would appreciate front end or back end solutions. In the back end, I actually have the data in associative arrays so I can do anything with it there.

JSON is designed as a subset of Javascript object literal notation. Any* valid JSON code is already valid to interpret as a JavaScript literal.
* Technically, a few rare whitespace characters are treated differently, but this is relevant to almost nobody.

Related

Will PHP json_decode() always preserve the array order from a JSON array?

Does the string
["first","second","third"]
always preserve array order and result in the PHP array
array('first','second','third');
when using json_decode()? I realize the answer is NO for objects, but I am asking about a string representing an array as input.
Yes. Arrays are ordered by definition, and JSON preserves this.
The JSON specification says:
An array structure is a pair of square bracket tokens surrounding zero or more values. The values are
separated by commas. The order of the values is significant.
The last sentence implies that a JSON encoder or decoder that changes the order is not in conformance with the specification. I can't find anything in the PHP documentation that explicitly says that it observes this requirement, but I think it can be assumed since it claims to be implementing JSON.
Yes order will be kept.
Alternatively you can use cast array to object, as order of object variables are not modified json_encode((object)$arr).

Could you ever legitimately have an occurrence of "}{" in a JSON string

I am generating a sequential string of independent JSON strings for insertion into a single field in my database (the means justify the end), and am wondering if a JSON string could ever legally have an occurrence of two opposing(ly) faced curly braces such as }{? As I would like to use this pattern as a delimiter if so.
I am using PHP's json_encode function for this purpose.
Should say that I don't mean as a value - or key if that were possible as I am in control of the data. Seems like a stupid question now.
Yes. It can form part of a string in JSON text.
{
"EskimoKiss": "}{"
}
If you must store multiple pieces of data expressed as JSON in a database field, then parse them to objects, wrap them in an array, then serialise that array to JSON and store that.
You really should normalise the data though.

What is data serialization?

First of all, I couldn't get clear definition of it from WikiPedia or even from serialize function in the PHP manual. I need to know some cases where we need the term serialization and how things are going without it? In other words, Where you need serialization and without it your code will be missing some important feature.
What is serialization?
Serialization encodes objects into another format.
For example you have an array in PHP like this:
$array = array("a" => 1, "b" => 2, "c" => array("a" => 1, "b" => 2));
And then you want to store it in file or send to other application.
There are several format choices, but the idea is the same:
The array has to be encoded (or you could say "translated"), into text or bytes, that can be written to a file or sent via the network.
For example, in PHP, if you:
$data = serialize($array);
you will get this:
a:3:{s:1:"a";i:1;s:1:"b";i:2;s:1:"c";a:2:{s:1:"a";i:1;s:1:"b";i:2;}}
This is PHP's particular serializing format that PHP understands, and it works vice versa, so you are able to use it to deserialize objects.
For example, you stored a serialized array in a file, and you want it back in your code as an array:
$array = unserialize($data);
But you could choose a different serialization format, for example, JSON:
$json = json_encode($array);
will give you this:
{"a":1,"b":2,"c":{"a":1,"b":2}}
The result is not only easily saved, read by human eye, or sent via network, but is also understandable by almost every other language (JavaScript, Java, C#, C++, ...)
Conclusion
Serialization translate objects to another format, in case you want to store or share data.
Are there any situations, where you cannot do anything, but serialize it?
No. But serialization usually makes things easier.
Are JSON and PHP format the only possible formats?
No, no, no and one more time no. There are plenty of formats.
XML (e.g. using a schema like WSDL or XHTML)
Bytes, Protobuf, etc.
Yaml
...
...
Your own formats (you can create your own format for serialization and use it, but that is a big thing to do and is not worth it, most of the time)
Serialization is the process of converting some in-memory object to another format that could be used to either store in a file or sent over the network. Deserialization is the inverse process meaning the actual object instance is restored from the given serialized representation of the object. This is very useful when communicating between various systems.
The serialization format could be either interoperable or non-interoperable. Interoperable formats (such as JSON, XML, ...) allow for serializing some object using a given platform and deserializing it using a different platform. For example with JSON you could use javascript to serialize the object and send it over the network to a PHP script that will deserialize the object and use it.
The serialize() PHP function uses an non-interoperable format. This means that only PHP could be used to both serialize and deserialize the object back.
You could use the json_encode and json_decode() functions in order to serialize/deserialize PHP objects using the JSON interoperable format.
Serialization is the process of turning data (e.g. variables) into a representation such as a string, that can easily be written and read back from for example a file or the database.
Use cases? There are many, but generally it revolves around the idea of taking a complex, nested array or object and turning it into a simple string that can be saved and read later to retrieve the same structure. For example, provided you have in php:
$blub = array();
$blub['a'] = 1;
$blub['a']['b'] = 4;
$blub['b'] = 27;
$blub['b']['b'] = 46;
Instead of going through every array member individually and writing it one could just:
$dataString = serialize($blub);
And the serialized array is ready to be written anywhere as a simple string, in such a way that retrieving this string again and doing unserialize() over it gets you the exact same array structure you had before. Yes, it's really that simple.
I need to know some cases we need the term serialization and how things are going without it?
Serialization can become handy if you need to store complete structures (like an invoice with all associated data like customer address, sender address, product positions, tax caclulcations etc) that are only valid at a certain point in time.
All these data will change in the future, new tax regulations might come, the address of a customer changes, products go out of life. But still the invoice needs to be valid and stored.
This is possible with serialization. Like a snapshot. The object in memory are serialized into a (often like in PHP) binary form that can be just stored. It can be brought back to live later on (and in a different context). Like with this invoice example: In ten years, the data can still be read and the invoice object is the same as it was ten years earlier.
In other word, Where you must need serialization and without it your code will be missing some important feature.
That was one example. It's not that you always needs that, but if things become more complex, serialization can be helpful.
Since you've tagged it with javascript, one kind of serialization could be form serialization.
Here are the references for the jQuery and prototype.JS equivalents.
What they basically do is serialize form input values into comma-separated name-value pairs.
So considering an actual usage..
$.ajax({
url : 'insert.php?a=10,b=15' //values serialized via .serialize()
type: 'GET'
});
And you would probably do $GET["a"] to retrieve those values, I'm not familiar with PHP though.

escape all data in an object

I have a object with some data being posted to a php script from a javascript. This data is coming from a for, so the user will will out a form, when they hit enter an Ajax script will take the form database, put it into an object then post it to my php encoding it with JSON.
Now i'm new to stuff like JSON so im not 100% sure what its doing, i've read a bit online and my conclusion is that it encodes the data with a sort of universal encoding that all programming languages have..... Maybe not the best description of it but hey. So this isn't doing the same thing as escaping the data is it?
Any, before i process the data and put in into a database i want to escape it but im not sure of the best way to go about this? is there a way i could escape the hole object? Any tips or tricks for this sort of thing?
No, jsons are't escaped at all.
On PHP side you could use json_decode to retrive a decoded form of the data then you will access all of the original object property as a PHP array.
JSON indeed is "universal" in that it is UTF-8 by default, and multi-byte sequences are escaped in \uuuuu format.
However, if you want to store the entire JSON object in the database as-is, that doesn't take away the need to escape the entire string before you insert it into the database, using the string escaping function of your database (or parametrized queries if your library supports them).
Encoding something in JSON is no the same as escaping it. Basically JSON is a serialization format based on Javascript object literals. So on the php side you need to:
Decode the json to PHP
Validate the vales
Escape the values
Insert the values into your db
After you decode the JSON you will be left with an array (see json_decode, and pass true as the second arg to make sure its an array and not a mic of stdObject and arrays).
So then you can pull out the data you ned and escape it you normally would any array passed to you through $_POST before insertion.

Encoding large numbers with json_encode in php

I have a php script that outputs a json-encoded object with large numbers (greater than PHP_MAX_INT) so to store those numbers internally, I have to store them as strings. However, I need them to be shown as un-quoted numbers to the client.
I've thought of several solutions, many of which haven't worked. Most of the ideas revolve around writing my own JSON encoder, which I have done already, but don't want to take the time to change all the places I have json_encode to instead say my_json_encode.
Since I have no control over the server, I cannot turn remove the JSON library. I cannot undeclare json_encode, nor can I rename it. Is there any easy way to handle all this, or is the best option to just go through each and every file and rename all the method calls?
With javascript being loosely typed, why the need to control the type in the JSON data? What are you doing with this number in javascript, and would parseInt\parseFloat not be able to make the leap from string to number on the client side?
The only option I had was to use my own json_encode method renamed to my_json_encode, and then change everywhere that called that method.

Categories