I have a JSON result in PHP that looks like the following:
[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]
I want to eliminate the Attributes (which contains Type and URL) so that the JSON result is flattened. So I'd like it to look more like:
[{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"}]
What is the best way in PHP to eliminate every instance of attributes?
//assign the orignal string to variable $json
$json = '[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]';
//decode the string with json_decode();
$decoded = json_decode($json);
//loop over the decoded array and populate array with Id and Name only
foreach($decoded as $d) $newarr[] = array('Id' => $d->Id, 'Name' => $d->Name);
//json encode the resulting array.
$finalJSON = json_encode($newarr);
Using json_decode(), array_map() and json_encode() should be easy enough:
function strip_arguments( $item){
$new_result = array(
'Id' => $item['Id'],
'Name' => $item['Name'],
)
return $new_result;
}
$array = json_decode( $input);
$array = array_map( 'strip_arguments', $array);
$input = json_encode( $array);
You of course may use unset() inside strip_arguments (instead of creating new array) but this will make sure any "new attribute" won't make it trough.
You can use return array(...) instead of declaring variable and chain operations to: json_encode(array_map( 'strip_arguments', json_decode( $input))); too :)
Using PHP's JSON's tools you can convert the JSON string into an array, from here use a simple foreach statement and REGEX to delete array entries.
Once this is done simply convert back into a JSON string using PHP functions and do with it as you please :-)
The functions I am thinking off are - json_decode, json_encode.
Thanks
Andrew
Related
I have converted an array in JSON. But the conversion puts arrays inside the JSON object.
My conversion is this:
{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}
Have you can beginning in key "0":{"make":"Mercedes-Benz"}, the interior of the JSON changes anI i can not submit it to an api.
I need my JSON object to be entirely like its beggining:
"title":"acastro","description":"teste acastro 4","category_id":29,"make":"Mercedes-Benz","model":"GLC220",...
and so on.
I tried with json_encode and JSON_FORCE_OBJECT but without luck.
Any solutions?
You can try below code but its not tested:
$json = '{"title":"acastro","description":"teste acastro 4","category_id":29,"region_id":3,"city_id":3158063,"district_id":"1","contact":{"person":"Classe Car"},"0":{"make":"Mercedes-Benz"},"1":{"model":"GLC 220"},"2":{"engine_code":"Classe A"}}';
$newArr = array();
function recursiveArrayShiftToRoot($array, &$newArr=array()){
global $newArr ;
foreach($array as $index=>$eachMixVal){
if(is_array($eachMixVal)){
recursiveArrayShiftToRoot($eachMixVal);
}else{
$newArr[$index] = $eachMixVal;
}
}
}
recursiveArrayShiftToRoot(json_decode($json, true), $newArr);
[{"id":2,"name":"Paypal"},{"id":3,"name":"Scrill"}]
How to add dynamically new attribute and its value in here using php or in laravel framework. converted data is like
[{"id":2,"name":"Paypal","amount":"100"},{"id":3,"name":"Scrill","amount":"200"}]
In pseudo code:
Convert JSON string to PHP associative array.
Add / alter keys on PHP associative array.
Convert PHP associative array to JSON string.
I don't want to take all the fun away - so here are some links:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
;-)
Update: OP has requested a complete solution.
To convert the JSON string to a PHP associative array:
$decoded = json_decode($jsonStr, true);
Always check that things didn't go wrong:
if ($decoded === null) {
die('Unable to decode JSON string: ' . $jsonStr);
}
Modify your PHP array:
$decoded[] = array(
'id' => 3,
'name' => 'Scrill',
'amount' => 200
);
Finally re-encode to a JSON string:
echo json_encode($decoded);
Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode
I have a JSON file named 'jason_file.json' that is look like:
[
{"name":"name1", "city":"city1", "country":"country1"},
{"name":"name2", "city":"city2", "country":"country2"},
{"name":"name3", "city":"city3", "country":"country3"},
{"name":"name4", "city":"city4", "country":"country4"},
{"name":"name5", "city":"city5", "country":"country5"}
]
Using for loop, I want to remove first two objects from file and save remaining objects in the same order in the 'jason_file.json'. Required result should be:
[
{"name":"name3", "city":"city3", "country":"country3"},
{"name":"name4", "city":"city4", "country":"country4"},
{"name":"name5", "city":"city5", "country":"country5"}
]
How can I do it?
Try this:
<?php
$json = '[
{"name":"name1", "city":"city1", "country":"country1"},
{"name":"name2", "city":"city2", "country":"country2"},
{"name":"name3", "city":"city3", "country":"country3"},
{"name":"name4", "city":"city4", "country":"country4"},
{"name":"name5", "city":"city5", "country":"country5"}
]'; //file_get_contents('jason_file.json');
$json = json_encode(array_slice(json_decode($json, true), 2));
/* (1) decode the JSON string
<-----------
(2) cut off the first two elements
<-----------
(3) recode as JSON
*/
echo $json;
//file_put_contents('jason_file.json, $json);
Output:
[{"name":"name3","city":"city3","country":"country3"},{"name":"name4","city":"city4","country":"country4"},{"name":"name5","city":"city5","country":"country5"}]
To make sure you end up with valid json, I would not edit the file manually.
Instead, read the file, parse the json, use array_shift() or something similar to remove the first two elements in the array, encode the resulting array as json and put it back in the file.
Well firstly, you will want to pull the file into a string. So
$str = file_get_contents('/path/to/my/file');
Then you will want to decode the string contents.
$arr = json_decode($str, true);
Finally shift the array twice
$arr = array_shift($arr);
$arr = array_shift($arr);
Or alternatively, slice the array
$arr = array_slice($arr, 2);
Finally, you can place the json string back into a file.
$newJson = json_encode($arr);
file_put_contents('/path/to/saved/file', $newJson);
Hope this helps!
using the below code for decoding json
$categories = json_decode($data);
$categories = $categories->data;
where i get this
{"categories":[{"id":1,"name":"Utilities","apps":897,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/uti.jpg"},{"id":2,"name":"Productivity","apps":477,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/pro.jpg"},{"id":3,"name":"Music","apps":466,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/mus.jpg"},{"id":4,"name":"Travel","apps":289,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/tra.jpg"},{"id":5,"name":"Navigation","apps":297,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/nav.jpg"},{"id":6,"name":"Books","apps":271,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/boo.jpg"},{"id":7,"name":"Healthcare & Fitness","apps":250,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/hea.jpg"},{"id":8,"name":"Games","apps":5116,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/gam.jpg"},{"id":9,"name":"Social Networking","apps":272,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/soc.jpg"},{"id":10,"name":"Lifestyle","apps":434,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/lif.jpg"},{"id":11,"name":"Finance","apps":200,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/fin.jpg"},{"id":12,"name":"News","apps":128,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/new.jpg"},{"id":13,"name":"Photography","apps":481,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/pho.jpg"},{"id":14,"name":"Entertainment","apps":1251,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/ent.jpg"},{"id":15,"name":"Business","apps":221,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/bus.jpg"},{"id":16,"name":"Sports","apps":199,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/spo.jpg"},{"id":17,"name":"Education","apps":433,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/edu.jpg"},{"id":18,"name":"Medical","apps":262,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/med.jpg"},{"id":19,"name":"Weather","apps":64,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/wea.jpg"},{"id":20,"name":"Reference","apps":419,"iconurl":"http:\/\/static.apptrackr.org\/caticons\/ref.jpg"}]}
and i would like to convert to in an array like this
Array[0]
{
id => 1
name => Utilities
apps => 897
iconurl => http:\/\/static.apptrackr.org\/caticons\/uti.jpg
}
and so on
This looks like a JSON string. You can use json_decode() to convert it into a PHP variable, e.g.
$obj = json_decode($json);
print_r($obj->categories); // array of StdClass objects
You can access and iterate the categories array regularly
echo $obj->categories[0]->name; // Utilities
echo $obj->categories[1]->name; // Productivity
echo $obj->categories[2]->name; // Music
To convert the StdClass objects to arrays, you could do
$categories = array();
foreach (json_decode($json)->categories as $category) {
$categories[] = (array) $category;
}
print_r($categories);
You could also do it with a lambda function and array_map:
// Before PHP5.3
$categories = array_map(
create_function('$el', 'return (array) $el;'),
json_decode($json)->categories);
// After PHP5.3
$categories = array_map(
function($el) { return (array) $el; },
json_decode($json)->categories);
Erm, you can just set the 2nd parameter to convert JSON into an array instead of into an object:
$categories = json_decode($data, true);
take a look at get_object_vars
http://php.net/manual/en/function.get-object-vars.php
#Gordon seems correct - that looks like JSON. Assuming, though, that you're dealing with an "actual" PHP Object, then it will be iterable; simply run through it with a foreach and push each key/value pair into your destination array.