Python to PHP | String to Multidimensional Json Object To Array - php

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
)
)

Related

How to convert JSON string to PHP object or array creation *code* [duplicate]

This question already has answers here:
print an array as code
(4 answers)
Closed 4 years ago.
FIRSTLY: This is a totally different question - How to convert JSON string to array
MY QUESTION...
I have a valid JSON string assigned to a php variable, $json.
I know that I can run it into json_decode($json, true); to parse into a php array at runtime, however I want to go a step beyond and convert this into a reusable php array code string, which can be simply copied and pasted into a php script, like $array = 'php array code here'.
For those who will inevitably ask "why?", an example:
to copy an example JSON endpoint parameter from an API's docs, then quickly convert to php array string code to paste into a test script as a valid test parameter for making a POST request
I know that I can do this:
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '<pre>';
echo '$phpArray = ' . print_r(json_decode($json));
echo '</pre>';
exit;
Which gets you close...
$phpArray = Array
(
[0] => stdClass Object
(
[ID] => 1
[Name] => Test One
)
[1] => stdClass Object
(
[ID] => 2
[Name] => Test Two
)
)
But there is of course still some work to do... currently I would copy this into Sublime Text or some other similar text manipulation tool and just use find/replace or regex find/replace in some cases. But what I am looking for is a quicker, more elegant solution whereby I could literally copy+paste that JSON into some script (or anywhere!), and run it to get this:
$phpArray = [
0 => [
'ID' => 1,
'Name' => 'Test One',
],
1 => [
'ID' => 2,
'Name' => 'Test Two',
],
];
Has someone created a good tool to do this already somewhere? I couldn't find anything. I am open to ANY elegant solution and will happily upvote any answer that is an improvement on this rudimentary means of bridging from the JSON to a PHP object / array creation code. Thanks!
<?php
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '$output = '.var_export(json_decode($json, true), true).';';
Output:
$output = array (
0 =>
array (
'ID' => '1',
'Name' => 'Test One',
),
1 =>
array (
'ID' => '2',
'Name' => 'Test Two',
),
);

I'm trying to decode json array to php but it's returning a blank page

I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.

JSON data revceiving PHP

The server receives from URL post string as below:
{
"head": {
"comm": 7,
"compress": false,
"ms": 1451029423348,
"encrypt": false,
"version": 2
},
"body": {
"data1": 0,
"data2": 59,
"data3": -40,
"data4": 0,
"data5": 0,
}
}
I have PHP file as below need to receive JSON format data from URL or java app sending post to server. Using server PHP ver 5.4.45, I can't change it.
$json = file_get_contents('php://input');
$string = get_magic_quotes_gpc() ? stripslashes($json) : $json;
$object = json_decode($string);
var_dump($object);
then i want to put to array each item in to array into $data variable each fields into $data array
I always receiving NULL , What can be the problem ?
If I paste your json here: http://jsonlint.com/ it gives a "Error: Parse error on line 14:"
Maybe it helps when you remove the comma after "data5": 0,
The JSON data is not correct. Try after removing the , after "data": 0.
Correct JSON :
{
"head": {
"comm": 7,
"compress": false,
"ms": 1451029423348,
"encrypt": false,
"version": 2
},
"body": {
"data1": 0,
"data2": 59,
"data3": -40,
"data4": 0,
"data5": 0
}
}
If, as you say, $json is NULL, the comma after "data5" is only because of text that was cut to make pasted code shorter, and you're using PHP <5.6 then according to http://php.net/manual/en/wrappers.php.php it could only be that either:
you're reading php://input multiple times (if not you then maybe a framework you're using or whatever);
the sender is passing data to you as multipart/form-data, which php://input cannot read.
try this:
$json = file_get_contents('php://input');
$string = get_magic_quotes_gpc() ? stripslashes($json) : $json;
$object = json_decode($string);
By using foreach function walk thru object elements and typecast them as an array
foreach($object as $k=>$v){
$data[$k] = (array)$v;
}
and the result will be as follows:
Array
(
[head] => Array
(
[comm] => 7
[compress] =>
[ms] => 1451029423348
[encrypt] =>
[version] => 2
)
[body] => Array
(
[data1] => 0
[data2] => 59
[data3] => -40
[data4] => 0
[data5] => 0
)
)

Parsing JSON data with php - Data coming back empty

I have a piece of JSON that I'm parsing with php. I need to get one of the pieces of data out of it.
Here's the output of the json when I do a print_r:
Array ( [deviceId] => 07a9727e-3fe5-4f44-9765-134388241f39 [programId] => 3895 [serviceId] => 19977 [createdAt] => 2013-12-12T07:19:04.466Z [updatedAt] => 2013-12-12T07:19:04.466Z [objectId] => 7TxmL2GiXq )
Here's my code trying to extract deviceId:
$objectData = json_decode($data, true);
print_r($objectData);
$deviceId = $objectData->deviceId;
$deviceId is coming back empty.
Any help would be appreciated. Thanks.
Do this:
$deviceId = $objectData['deviceId'];
You are using the optional second parameter TRUE in your json_decode call, which converts it into an associative array instead of an object.
Alternatively:
$objectData = json_decode($data);
$deviceId = $objectData->deviceId; // Works

php json decode - get a value

I'm trying to extract a specific value from json content . Here it is link with the json code http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521 As you may see the the code displayed is
json({items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null});
I need to extract the first url which in this case is "http://fairfield.ebayclassifieds.com/" and its name value which is "Fairfield" , I could do it with regex but I would prefer to use json_decode. Unfortunately when I try to decode it doesn't work
$json = getContent("http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521");
$test = json_decode($json, true);
As danp already said, the returned JSON is enclosed in a function call (specified by jsoncallback=json). You cannot get rid of this totally but, just using AreaSearch?jsoncallback=&lat=41.1131514&lng=-74.0437521 removes at least the json at the beginning of the string and you can get rid of the brackets by:
$json = trim(trim($json), "();");
with gives:
{items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null}
Unfortunately, the JSON string is not valid. The keys (items, url, ...) have to be enclosed in quotes ". You can easily check that you get a syntax error with json_last_error() (error code 4, JSON_ERROR_SYNTAX).
Update:
According to this question: Invalid JSON parsing using PHP , you can make the JSON string valid with:
$json = preg_replace('/(\w+):/i', '"\1":', $json);
This encloses the keys in quotes.
If the string would be valid, then you could generate an array via:
$a = json_decode($json, true);
which would give you:
Array
(
[items] => Array
(
[0] => Array
(
[url] => http://fairfield.ebayclassifieds.com/
[name] => Fairfield
)
[1] => Array
(
[url] => http://newyork.ebayclassifieds.com/
[name] => New York City
)
)
[error] =>
)
So you could get the first URL and name via $a['items'][0]['url'] and $a['items'][0]['name'] resp.
But I repeat, the JSON you get as response is not valid and you cannot parse it with json_decode() in its original form.
Its not valid JSON. The keys should be wrapped inside quotes.
You can validate your json using the excellent JSON Lint site.
This is a valid version of the data returned:
{
"items": [
{
"url": "http://fairfield.ebayclassifieds.com/",
"name": "Fairfield"
},
{
"url": "http://newyork.ebayclassifieds.com/",
"name": "New York City"
}
],
"error": "null"
}

Categories