How conversion of data from JSON to php format happen - php

I am passing data to my php script using jQuery's .ajax method. I am passing a very complex JSON object as data. At server side I receive data in $_POST variable all converted to php format.
How this conversion happen? Does it happen at the client side or the server side? Which modules associated in this process. Any source to understand complete process in depth.
Client request:
var data = {
foo: 123,
bar: 456,
rows: [
{
column1 : 'hello',
column2 : 'hola',
column3 : 'bonjour',
},
{
column1 : 'goodbye',
column2 : 'hasta luego',
column3 : 'au revoir',
},
],
test1:{
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
At Server Side My '$_POST' var:
Array
(
[foo] => 123
[bar] => 456
[rows] => Array
(
[0] => Array
(
[column1] => hello
[column2] => hola
[column3] => bonjour
)
[1] => Array
(
[column1] => goodbye
[column2] => hasta luego
[column3] => au revoir
)
)
[test1] => Array
(
[test2] => Array
(
[test3] => baz
)
)
)
This code snippet is taken from here.

Jquery is converting the data into HTTP format. http://en.wikipedia.org/wiki/POST_%28HTTP%29
This link shows how arrays are encoded: http://php.net/manual/en/function.http-build-query.php
You can use PHP itself to generate the HTTP format. I converted your array to PHP format:
$data = array( 'foo' => 123,
'bar' => 456,
'rows' => array( 0 => array( 'column1' => 'hello',
'column2' => 'hola',
'column3' => 'bonjour'),
1 => array( 'column1' => 'hello',
'column2' => 'hola',
'column3' => 'bonjour')),
'test1' => array('test2' => array('test3' => 'baz')) );
Then you can generate the HTTP as follows:
echo http_build_query($data);
I got the following result:
foo=123&bar=456&rows%5B0%5D%5Bcolumn1%5D=hello&rows%5B0%5D%5Bcolumn2%5D=hola&rows%5B0%5D%5Bcolumn3%5D=bonjour&rows%5B1%5D%5Bcolumn1%5D=hello&rows%5B1%5D%5Bcolumn2%5D=hola&rows%5B1%5D%5Bcolumn3%5D=bonjour&test1%5Btest2%5D%5Btest3%5D=baz

JSON is a universal data exchange format (to all languages that support its specification that is). The JSON data is encoded from a memory object to a JSON-formatted string by the language that is sending it, and decoded (from string to object) by the language that receives it.
An important point when talking about jQuery and JavaScript is that the syntax for a JSON looks similar to JavaScript, but it is actually more strict than the syntax for a regular JavaScript Object (see: What are the differences between JSON and JavaScript object?). For example, the JavaScript object literal you have posted above is not valid JSON, becuase both the keys and values are not surrounded by quotes. Additionally, there is technically no such thing as a JSON Object. A glob of JSON data is acutally just a String written in a subset of JavaScript's Object Notation.
So, PHP's json_encode($object) function and jQuery's encodeJSON([Object]) function will transform a memory object in their respective languages into a string that both languages (and others of course) can accept as data. The json_decode($string) and parseJSON([String]) functions in PHP and jQuery, respectively, take a JSON string and commit it to memory as an object.

jQuery encodes the object data as a key value pairs, for example if we have:
var data = {
foo: 123,
bar: 456,
rows: [
{
column1 : 'hello',
column2 : 'bonjour',
},
{
column1 : 'goodbye',
column2 : 'au revoir',
},
]
};
jquery will encode that object to the following string
foo=123&bar456&rows[][column1]=hello&rows[][column2]=bonjour&rows[][column1]=goodbye&rows[][column2]=au+revoir
and PHP will convert that string in to an array and assign it to the $_GET or $_POST array depending of the request.

Related

Python to PHP | String to Multidimensional Json Object To Array

I have a python script which returns an object as string. I call this python script with php and then print out the result with var_dump(json_decode($result)) and get this (this it the right object I want so my python code works properly I guess):
string(467) "{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }} "
So as you can see its a string on php side.
But how can I convert it to an object now and the create a multidimensional array from it in php?
If you need more information pls ask Ill add it.
I tried:
json_decode($result, true);
json_decode($result);
$response = (array) $result;
all I get is an Array with 1 Index and the whole Object as Value in it.
The Object gets generated like this on python side:
for message in consumer:
if message.key == str.encode(sys.argv[1]):
returnValue = message.value #this here is an byte obj from external system
consumer.close()
print(returnValue.decode("latin-1"))
Edit 2 and Solution
After long search I found out that the service I'm using (3d Party) returns the result from the python script with json_encode(). I removed that and now this code works:
$array = json_decode($response, TRUE);
return var_dump($array);
Since it is a string you can decode it like this:
$string = '{"userData": {"geburtsdatum": "PMS_2018-01-01", "anrede": "PMS_Herr", "ID": "1", "nachname": "PMS_Nachname1", "Test": {"tel": "PMS_Tel1", "postalOptIn": 0, "postal": "S3_Postal1", "email": "PMS_EMail1"}, "vorname": "PMS_Vorname1" }}';
print_r(json_decode($string, true));
Which returns an array:
Array
(
[userData] => Array
(
[geburtsdatum] => PMS_2018-01-01
[anrede] => PMS_Herr
[ID] => 1
[nachname] => PMS_Nachname1
[Test] => Array
(
[tel] => PMS_Tel1
[postalOptIn] => 0
[postal] => S3_Postal1
[email] => PMS_EMail1
)
[vorname] => PMS_Vorname1
)
)

Parse string to array like CakePHP form data

I am looking for a way to parse strings in an array to an array which has a similar pattern to how CakePHP handles POST data. Or even a function in CakePHP that would do it.
UPDATED:
Current array:
array(
'data[callers]' => (int) 4,
'data[status]' => 'Unknown',
'data[country_id][107]' => (int) 1,
'data[country_id][150]' => (int) 0
)
Desired result:
array(
'callers' => (int) 4,
'status' => 'Unknown',
'country_id' => array(
(int) 107 => (int) 1,
(int) 150 => (int) 0
)
)
The purpose is saving serialized form data which can later be passed to a PHP function without having to POST the data from the browser.
The data comes from a form which was serialized and saved in the database. CakePHP generates input names in the form with brackets like this: data[country_id][107] and inside the controller you can access it like this $this->request->data['country_id']['107']
But when I serialize the form with javascript and save the raw JSON string in the database I need a way to make it into an array like CakePHP does.
Firstly make sure your array is valid first like:
$data = array (
'callers' => 4,
'status' => 'Unknown',
'country_id' => array(
'107' => 0,
'150' => 0
)
);
JSON ENCODE
Now you can json encode it
$json = json_encode($data);
echo $json; // prints: {"callers":4,"status":"Unknown","country_id":{"107":0,"150":0}}
See ^ it is now a string.
http://php.net/manual/en/function.json-encode.php
JSON DECODE
Then when you need it as an array call json_decode()
json_decode($data, true);
Note the second parameter is setting return array to true else you will get an the json returned as an object.
http://php.net/manual/en/function.json-decode.php

How to deserialize Perl Data::Dumper output in PHP

I have a result of export variable in Perl like this string:
$VAR1 = {
'guard' => undef,
'work_hand' => undef,
'images' =>
{'1' =>
{
'mini_height' => 150,
'width' => 150,
'extension' => 'jpg',
'filename' => 'object_1.1330907414.96873.jpg',
'mini_width' => 150,
'class' => 'Ontico::Image',
'height' => 150,
'mini_filename' => 'object_1.1330907414.96873.mini.jpg',
'size' => 26053,
'symname' => 'big_logo'
},
'2' =>
{
'width' => 48,
'extension' => 'jpg',
'alt' => 'Даниэле Галлоппа',
'height' => 48,
'mini_filename' => 'object_91.1235312905.mini.jpg',
'size' => 12809,
'symname' => 'logo',
'mini_height' => 150,
'filename' => 'object_91.1235312905.jpg',
'mini_width' => 150,
'class' => 'Ontico::Image'
}
},
'show_league_banner' => 0,
'back_hand' => undef,
'weight_category' => undef,
'stick_position' => undef
};
How can I deserialize this data in PHP?
P.S. I already have data in this format in DB, I cannot change it to json or another.
You've got a number of suggestions for trying to parse it one way or another, but the real question is why?
Why not just have a small Perl program that loads it, and spits out an equivalent JSON string.
You could then either call that Perl program from within your PHP to do the conversion; this would mean you are using Perl to read the Perl format, which would guarantee correct conversion.
Or (better yet) run it against your entire database in a batch, to get rid of the Perl-specific data format from the DB; then you can just use PHP's standard JSON functions.
That would then make life so much simpler in your PHP code (or in any other language you need to read the data with at a later date).
The obvious and only robust solution is to use Perl to deserialize and reserialize the input to a standard format. The Perl program that can accomplish this task does not need to be very large, either.
// receive input in Perl's Data::Dumper format and produce PHP object output
function perl_dd_to_php( $dd_output ) {
$process = proc_open( "perl -000 -MJSON -e 'print encode_json eval <>'",
array( array("pipe","r"), array("pipe","w") ),
$pipes );
fwrite($pipes[0], $dd_output );
fclose($pipes[0]);
$json_string = stream_get_contents($pipes[1]);
fclose($pipes[1]);
return json_decode($json_string);
}
Since it's not JSON but it looks like JSON, you could try to modify a JSON library to work with that format. I took this JSON library, replaced : with => and added undef as you can see here (lines 496, 671 and 681). It's pretty straightforward, really, and I assume you can work around other differences in a similar manner.
Result is:
stdClass Object
(
[guard] =>
[work_hand] =>
[images] => stdClass Object
(
[1] => stdClass Object
(
[mini_height] => 150
[width] => 150
[extension] => jpg
[filename] => object_1.1330907414.96873.jpg
[mini_width] => 150
[class] => Ontico::Image
[height] => 150
[mini_filename] => object_1.1330907414.96873.mini.jpg
[size] => 26053
[symname] => big_logo
)
[2] => stdClass Object
(
[width] => 48
[extension] => jpg
[alt] => Даниэле Галлоппа
[height] => 48
[mini_filename] => object_91.1235312905.mini.jpg
[size] => 12809
[symname] => logo
[mini_height] => 150
[filename] => object_91.1235312905.jpg
[mini_width] => 150
[class] => Ontico::Image
)
)
[show_league_banner] => 0
[back_hand] =>
[weight_category] =>
[stick_position] =>
)
Is that what you're looking for?
use JSON;
(or any other data interchange format like XML)
JSON documentation and examples are available at CPAN
If you can change the Perl code, then do as amon suggests and use some standard serialization format like JSON or XML or YAML that you can deserialize in PHP.
You could even make Perl output PHP's native serialization format if you really wanted to, although I wouldn't generally recommend that. (What about when you next want to deserialize the same data in, say, Python?)
If you can't change the Perl code, you'll just have to bite the bullet and try to parse the Data::Dumper output in PHP. I couldn't find any existing code to do that, so it looks like you may have to write your own. This could be job for a parser generator, although the format is (usually) simple enough that you might be able to just hand-code it.
Edit: Since you say that you have this serialized data in a database, why not just write a Perl program to read the data and convert it to a more standard serialization format like JSON?
Since you stated you cannot change format:
I don't like using eval, but because your syntax is so close to the expected PHP array syntax, I think we can let it slide.
Set $string equal to the contents from your database that fits the format below. See below for a working example using the data you provided. At the end of the day, PHP will set the variable at the beginning of your perl var to the new parsed array.
Since it is going to be a textblock/large string, do:
<?php
$string = "\$VAR1 = {
'guard' => undef,
'work_hand' => undef,
'images' =>
{'1' =>
{
'mini_height' => 150,
... // truncated for readability
};";
$res = str_replace(array("{", "}", 'undef'), array("array(", ")", "''"), $string);
eval($res);
print_r($VAR1);
Your result is:
Array
(
[guard] =>
[work_hand] =>
[images] => Array
(
[1] => Array
(
[mini_height] => 150 ...
Note: I would suggest you take the time now to retrofit and upgrade your database content to a more standard format simply for the fact that it will be easier to maintain in the future.
You can loop through your database, grab all the contents row by row, at which point you run the data into the function above, and wrap it in json_encode() and update your database row with the new JSON string. This will save you a headache in the future and allow you to update all your data for the new standard.

Jquery serialize to PHP array

I want to send the result of a HTML sorting to the server by serializing with jQuery.
This works if I only send the result:
var result = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: '/cms/update/',
data: result,
});
But I try to send a Javascript Object to the server wich contains the serialized 'result'
In PHP I get an array with result_2 as the serialize object:
Array
(
[ids_1] => miti_1_ti_2_col_2
[article_id] => article_id_2
[result_1] =>
[ids_2] => miti_1_ti_2_col_1
[result_2] => article_id[]=2
)
How can I get this result to be an array in PHP?
As I understood "result" is a serialized object too.
So you have to unserialize result at first.
Then you have to unserialize result2. Something like that:
$res1 = unserialize($data);
if (isset($res1['result_2']){
$res2 = unserialize($res['result_2']);
}
Updated:
I don't know if your result_2 in data is already serialized. Therefore here are two examples:
if result_2 is not serialized in data:
$arr = array('id_1' => 'miti_1_ti_2_col_2',
'article_id' => 'article_id_2',
'result_1' => '',
'ids_2' => 'miti_1_ti_2_col_1'
);
$arr['result_2'] = $arr;
$test1 = serialize($arr);
$test1 = unserialize($test1);
If result_2 is already serialized in data:
$arr = array('id_1' => 'miti_1_ti_2_col_2',
'article_id' => 'article_id_2',
'result_1' => '',
'ids_2' => 'miti_1_ti_2_col_1'
);
$arr['result_2'] = serialize($arr);
$test2 = serialize($arr);
$test2 = unserialize($test2);
$test2['result_2'] = unserialize($test2['result_2']);
This code works I checked out it. If your code still doesn't work check result in JS.
If I've understood correctly, you need to convert a string such as action[]=1&action[]=2 into an array?
If that is right you can use the following: (when $_POST["order"] = "action[]=1&action[]=2")
$result = preg_split("/&?action\[\]=/", $_POST["order"], -1, PREG_SPLIT_NO_EMPTY);
This will give you:
Array
(
[0] => 1
[1] => 2
)

Parsing JSON from PHP

I'm trying to iterate in a JSON object that is returned from a PHP script. The return part is something like:
$json = array("result" => -1,
"errors" => array(
"error1" => array("name" => "email","value" => "err1"),
"error2" => array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
So, in JavaScript I can do:
var resp = eval('(' + transport.responseText + ')');
alert(resp.length);
alert(resp.errors.error1.name);
But I can't do:
alert(resp.errors.length);
I would like to iterate errors, that's why I'm trying to get the length. Can somebody give me a hint? Thanks!
To be able to do that, you need resp.errors to be a Javascript array, and not a Javascript object.
In PHP, arrays can have named-keys ; that is not possible in Javascript ; so, when using json_encode, the errors PHP array is "translated" to a JS object : your JSON data looks like this :
{"result":-1,"errors":{"error1":{"name":"email","value":"err1"},"error2":{"name":"pass","value":"err2"}}}
Instead, you would want it to look like this :
{"result":-1,"errors":[{"name":"email","value":"err1"},{"name":"pass","value":"err2"}]}
Notice that "errors" in an array, without named-keys.
To achieve that, your PHP code would need to be :
$json = array(
"result" => -1,
"errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
(Just remove the named-keys on errors)
Have a look at your JSON output. resp.errors will be something like this:
{"error1": {"name": "email", "value": "err1"}, ...}
As you can see, it's an object, not an array (since you passed it an associative array and not an numerically indexed array.) If you want to loop through an object in JavaScript, you do it like this:
for (var error in resp.errors) {
alert(resp.errors[error].name);
}
If you want it to be a JavaScript array, your PHP should look like this:
$json = array("result" => -1, "errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "email","value" => "err1")
));
If you inspect the evaluated object in Firebug, you would see that "errors" is not an array but an object(associated arrays in PHP translates to object in JS). So you need to use for-in statement to iterate through an object.
You need to check every property name with hasOwnProperty to be sure that it is something you have sent, not some prototype property.

Categories