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
Related
I am consuming a web service that returns some XML data. The problems start when I convert the xml data to json. Some elements that are supposed to return an array of objects, when they have only one value, they are not converted to an array with a single object inside, they turn into an object. So instead of having:
{
"products":[ { "title":"Title 1", "attributes":[{"color":"blue"}] } ]
}
I get
{
"products":{ "title":"Title 1", "attributes":{"color":"blue"} }
}
and the php array looks like this
[products] => Array ( [title] => Title 1 [attributes] => Array ( [color] => blue ) )
instead of this
[products] => Array ( [0] => Array ( [title] => Title 1
[attributes] => Array ([0] => Array ([color] => blue ) ) )
So what I have done is the below:
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
if (isset($array['products']) && !isset($array['products'][0])) {
$array['products'] = array($array['products']);
}
I check if there is an array named products and if it doesn't have an index 0, I nest it inside a new array.
This does the job. Then I do the same for the attributes array like this:
$products = $array['products'];
$array['products'] = [];
foreach ($products as $product) {
if (isset($product['attributes']) && !isset($product['attributes'][0])) {
$product['attributes'] = array($product['attributes']);
}
array_push($array['products'], product);
}
Here, I bind the products array to a variable called products to use it in the loop, then I empty the array and after I create the new attributes array, I populate the products array with the changed products.
My question is:
Is there a better way to deal with this thing? I don't like what I am doing here, but I can't think of anything else...
EDIT
This is my soap request:
$client = new SoapClient($wsdl, $soapOptions);
$soapHeader = WsSecurity::createWsSecuritySoapHeader($username, $password, false, $synced, 60, true, true, false, true);
$client->__setSoapHeaders($soapHeader);
$response = $client->dateRetrieveMovement($dateMovementRequest);
$movements = $response->DateMovementRequestResult->movements;
$movementInfo = $movements->movementInfo;
$messages = $movementInfo->messages->messageExchanged;
$messageData = $messages->IEMessage->xmlData;
$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);
The question is "is there a better way of doing the XML to JSON conversion", and I think the answer is "not without doing some coding".
Standard XML-to-JSON conversion libraries simply don't know enough about the semantics of your data model to produce a decent representation of your data. In theory a tool could try an extract such information from a schema, or elsewhere, but I don't know of any that does.
Writing a custom XSLT transformation to produce exactly the JSON you want is not too difficult, especially with XSLT 3.0, and this may well be less effort than patching up the JSON in the receiving application in the way you describe.
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
)
)
I am using this php library to communicate with the spotify api to get my user details. The spotify api returns user data which I then want to add to a json file. Basically, whatever is sent back from the api I want to append to the json file for each user.
The data returned from the api looks like the following when I do print_r($api->me()); This is basically coming from this api call.
stdClass Object ( [display_name] => Paul Flanagan
[email] => paulflanagan#gmail.com
[external_urls] => stdClass Object (
[spotify] => https://open.spotify.com/user/21aydctlhgjst3z7saj2rb4pq ) [followers] => stdClass Object (
[href] => [total] => 19 )
[href] => https://api.spotify.com/v1/users/2391231jasdasd1
[id] => 21aydctlhgjst3z7saj2rb4pq
[images] => Array ( [0] => stdClass Object (
[height] => [url] => https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/18301863_452622995075637_5517698155320169855_n.jpg?oh=9e949fafd3ee84705ea5c1fa1aa9c811&oe=59C9F63C
[width] => ) ) [type] => user [uri] => spotify:user:21aydctlhgjst3z7saj2rb4pq )
I want to write this code to a json file
I have attempted many approaches but as I am more javascript focused than php I am struggling to write the data correctly. My latest attempt at the code looks like this:
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'KEY1',
'KEY2',
'CALLBACK_URL'
);
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
$api->setAccessToken($session->getAccessToken());
$file = "users.json";
$json = json_decode(file_get_contents($file), true);
$file = fopen($file,'w+');
fwrite($file, $api->me());
fclose($file);
print_r($api->me());
} else {
$options = [
'scope' => [
'user-read-email',
],
];
header('Location: ' . $session->getAuthorizeUrl($options)$
die();
}
?>
As $api->me() returns object - you cannot write it to a file directly. You should convert object to a string. Simple way is to json_encode it:
$file = "users.json";
$json = json_decode(file_get_contents($file), true);
$file = fopen($file,'w+');
fwrite($file, json_encode($api->me()));
fclose($file);
Next problem - is overwriting data. As you open file with w+ - you file gets truncated to 0 length.
Solution here depends on what you need with previous data. If you want to rewrite some data - I think current behaviour does it already.
If you want to append data to a file - you should use another mode when you open file, for example a+. But in this case, file contents won't be correct json, as you write to file not a single json string, but several strings, which is not correct json. So, it's up to you to find a proper solution.
Update:
According to file name, I suppose you store users in it. So, I think there's a list of users, encoded in json. So, a brief solution can be:
$file = "users.json";
$json = json_decode(file_get_contents($file), true);
// Now $json stores list of you current users. I suppose it's a simple array of arrays
// This is data for a new user
$new_user = $api->me();
// as data `$new_user` is object, I think you need to convert it to array
// this can be done as:
$new_user = json_decode(json_encode($new_user), true);
// now, add new user to existsing array
$json[] = $new_user;
$file = fopen($file,'w+');
// now we can encode `$json` back and write it to a file
fwrite($file, json_encode($json));
fclose($file);
I have this data:
Array
(
[id] => 19936953
[name] => Zackaze
[profileIconId] => 585
[summonerLevel] => 30
[revisionDate] => 1394975422000
)
$str = json_decode($data,true);
$row = (object) $str;
echo $row['name'];
I tried this code but it constantly gives this error:
Fatal error: Cannot use object of type stdClass as array
Hopefully you can help me.
While the conversion to an object is unnecessary (as others have mentioned), that is not the cause of your error. You cannot access object properties using $array['key'] notation. You must use $object->property.
Alternatively, you can remove the $row = (object) $str; line, and then you can access $row as an array.
You already have decoded your json as an associative array since you used true as second parameter so you can print it directly with scopes. If you need to decode as an object simply remove the second parameter, I think you will need to access it in another way though.
$str = json_decode($data,true);
echo $str['name'];
The second argument of json_decode will convert the Object into a Associative Array. Just remove the second argument or change it to false and it will return a stdClass instead of a Associative array.
You can see the Documentation.
Try outputting like
$str = json_decode($data,true);
$str = array
(
'id' => 19936953,
'name' => Zackaze,
'profileIconId' => 585,
'summonerLevel' => 30,
'revisionDate' => 1394975422000
);
$row = (object) $str;
echo $row->name;
Or a cleaner way
$str = json_decode($data);
echo $str->name;
I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array.
Here is what I've tried:
print_r($json_obj) yields:
Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) )
print_r($json_obj[0][1]) yields:
featured
print_r($json_obj[1][0]) yields:
uploads/featured/moon-5469.jpg
print_r($json_obj[1][1]) yeilds:
featured
print_r($json_obj[0][0]) yields:
uploads/featured/doublewm-4097.jpg
PHP Code:
<?php
$resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"],
["uploads/featured/moon-5469.jpg","featured"]]';
$json_obj = json_decode($resultSet);
// print_r($json_obj);
print_r($json_obj[0][1]);
?>
The JSON validates per JSONLint
[
[
"uploads/featured/doublewm-4097.jpg",
"featured"
],
[
"uploads/featured/moon-5469.jpg",
"featured"
]
]
I would like to end up with a object with all the keys in the json_obj... ie:
json_obj = array(
'uploads/featured/moon-5469.jpg',
'uploads/featured/doublewm-4097.jpg'
);
If your input is always in the same format, you can handle it like this
$tmp = json_decode($resultSet);
$json_obj = array();
foreach ($tmp as $values) {
array_push($json_obj, $values[0]);
}
This will give you $json_obj in the desired format with a hardcoded $resultSet like the one you provided.
maybe this is what you are looking for:
json encode server-side like:
echo json_encode($html);
json parse clientside like
var str = JSON.parse(data);
alert (JSON.stringify(str))
I managed to fix it like this:
Changing the json object to this format
data = { gallery: gallery_name,
files: [
// imagefile,imagefile,imagefile...
]
};
And the using the following php
$resultSet = json_decode($_GET['submittedResults'], true);
$gallery = $resultSet['gallery'];
$files_to_zip = $resultSet['files'];