How to remove the unwanted nested keys from JSON - php

This is my json:
{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}
I want to remove the second level keys (e.g "26:" and "28":) using PHP.
In other words, I want to replace the double-quoted number keys with zero-indexed numeric keys.
How can I make it look like this:
{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}

Here is the demo.
Code:
// declare $json
$array=json_decode($json,true); // decode as array
// overwrite subarray with zero-indexed keys while preserving subarray values
$array['all_counts_reports']=array_values($array['all_counts_reports']);
var_export(json_encode($array)); // return to json
Input:
$json='{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}';
Output:
'{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}'
In your javascript, use JSON.parse() to strip the wrapping single quotes:
var str='{"all_counts_reports":[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]}';
var json=JSON.parse(str);
console.log(json);
And because we are running with assumptions, if you want to remove the all_counts_reports key as well, you can use this one-liner:
Code:
$new_json=json_encode(array_values(current(json_decode($json,true))));
Output:
'[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]'

$array = json_decode($your_json_string,true);
print_r($array);
$result = array();
foreach($array['all_counts_reports'] as $rep){
$result['all_counts_reports'][] = array(
"name"=>$rep['name'],
"date"=>$rep['date'],
"trips_per_day"=>$rep['trips_per_day'],
"cash_trips"=>$rep['cash_trips'],
"credit_trips"=>$rep['credit_trips'],
"compliment_trips"=>$rep['compliment_trips'],
);
}
$result_json = json_encode($result);
echo $result_json;
There may be better solution, but this one is right now in my mind
Its unclear that what you looking for, if you just want to remove and dont want to maintain as original json then you can do like this example. But if you dont want your all_counts_reports treated as array [] then this example will not help.
And simply pass to android then above will work.

Related

JSON Object to string with PHP / JavaScript

I have below JSON object, that is being posted from my frontend to my backend with Axios:
this.columns = JSON.parse(this.columns);
This can look like:
columns: {
1: {
position: "10"
},
2: {
position: "35"
},
3: {
position: "20"
}
}
Now, I need to sort this JSON object on my backend from lowest to highest position and then convert the JSON object to a string (because I am using the values in another command line input):
"{\"1\":{\"position\":\"10\"},\"2\":{\"position\":\"20\"},\"3\":{\"position\":\"35.00\"}}"
I am trying to sort this and then convert it to a string with PHP:
//Sort the columns
sort($this->columns);
$columns = json_encode($this->columns);
But this returns the columns as an array:
"[{"position":"10"},{"position":"20"},{"position":"35"}]"
How can I sort the JSON object, but return it as a string so I can use it on the command line?
I think This is What You Need
First Variant:
json_encode($this->columns, JSON_FORCE_OBJECT);
Second Variant
json_encode((object) $this->columns);
This gives you Json Object String
Example:
{"0":{"position":"10"},"1":{"position":"20"},"2":{"position":"35"}}
Consider Upvote if this answer helps you
You can json_decode with true flag and use array_multisort,
$temp = json_decode($temp['columns'], true);
array_multisort(array_column($temp['columns'], "position"), SORT_ASC, $temp['columns']);
echo json_encode($temp['columns']);
Demo.
Output:-
[{"position":"10"},{"position":"20"},{"position":"35"}]

How to correctly parse JSON in PHP

I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id

How to access JSON element using regex or array index in PHP

I am trying to read JSON elements "unit" and "value" using PHP. However, some JSON elements ("local/sysbench-cpu-1.0.0", "m4.4xlarge-4.4.0-66-generic") may not be the same in each JSON. That is why I want to use regex or the array index to access elements rather then a particular string:
{
"title": "cputests-sysbench-cpu-100-m4-4xlarge-20170328",
"results": {
"local\/sysbench-cpu-1.0.0": {
"arguments": "cpu performance benchmark",
"units": "seconds",
"results": {
"m4.4xlarge-4.4.0-66-generic": {
"value": "53.2386"
}
}
},
"": {
"arguments": "Memory Usage Monitor",
"units": "Megabytes",
"results": {
"m4.4xlarge-4.4.0-66-generic": {
"value": "1355,1356,1357,1357,1358,1359,1358,1359,1359,1358,1357,1358,1369,1370,1374,1373,1374,1376,1370,1362,1359,1360,1358,1358,1357,1358,1360,1360,1359,1359,1362,1362,1362,1363,1362,1363,1366,1365,1369,1366,1365,1363,1362,1363,1362,1363,1363,1363,1368,1374,1373,1372,1372,1373"
}
}
}
}
}
The PHP script works if I don't use regex or array index:
<?php
$string = file_get_contents("result.json"); <br>
$data = json_decode($string); <br>
//$data = json_decode($string, true);
//var_dump(json_decode($string)); <br>
print $data->{'results'}->{**'local/sysbench-cpu-1.0.0'**}->units; <br>
print "\n";<br>
print $data->{'results'}->{'local/sysbench-cpu-1.0.0'}->{'results'}->{'**m4.4xlarge-4.4.0-66-generic**'}->value; <br>
// print $data['results']['local/sysbench-cpu-1.0.0']['units']; <br>
// print "\n"; <br>
// print $data['results']['local/sysbench-cpu-1.0.0']['results']['m4.4xlarge-4.4.0-66-generic']['value']; <br>
?>
Any attempt to use regex in place of a string or array index when using json_decode($string, true) fails.
You can use a foreach loop to go over the results...
foreach ($json->results as $key => $results) {
...
// access to $results->units
foreach ($results as $x => $item) {
...
// access to $item->value
}
}
Then it won't matter what they key is. Something along those lines.
PHP's JSON parsing only returns a plain old associative array, or an object. Neither of these support using regexes as lookups. If you insist on using native PHP, you'll have to foreach your way through the keys and values.
Or, you might take a look at something like JsonPath which allows you to load up JSON, and then use a query string that looks very close to shell globbing:
$data = ['people' => [['name' => 'Joe'], ['name' => 'Jane'], ['name' => 'John']]];
$result = (new JSONPath($data))->find('$.people.*.name'); // returns new JSONPath
So in your case, your find() string would be something like $.results.*.units for the unit values, and $.results.*.results.*.value for the values. There's probably an even fancier query string that would return both units and values at the same time.

Decoding Nested JSON in PHP

Excuse me if this has been covered, but I've looked and can't find an answer that works.
I have the following JSON (shortened for clarity):
[{
"header": {
"msg_type": "0001"
},
"body": {
"event_type": "ARRIVAL",
"train_id": "384T22MJ20"
}
},{
"header": {
"msg_type": "0003"
},
"body": {
"event_type": "DEPARTURE",
"train_id": "382W22MJ19"
}
}]
Now I know I can use json_decode to create a php array, but not knowing much about php I don't know how to get it to do what I want. I need to be able to access a value from each array. For example I would need to extract the train_id from each array. At the moment I have this:
$file = "sampleData.json";
$source = file_get_contents($file);
$data = json_decode($source);
$msgbdy = $data->body;
foreach($msgbdy as $body){
$trainID = $body->train_id;
}
I know this is wrong, but I'm not sure if I'm on the right track or not.
Thanks in advance.
anonymous objects are deserialized as array-members, foreach can handle that :
$objs = json_decode($source)
foreach($objs as $obj)
{
$body = $obj->body; //this is another object!
$header = $obj->header; //yet another object!
}
and within that loop, you can now access msg_type, train_id and event_type via $body and $header
I suggest to pass it true as a parameter, it is easier to work with associative arrays than objects:
$messages = json_decode($source, true);
foreach($messages as $message){
$trainID = $message["body"]["train_id"];
}
You process it in the wrong order: your string is an array of objects. Not an object with arrays.
You first need the large foreach loop to iterate over the array and then access for each element the "body" and "train_id".
Your code should thus read:
foreach($data as $item) {
echo $item->body->train_id; //or do something else with $item->body->train_id
}
Maybe something like:
$data = json_decode($source);
foreach ($data as $message) {
$trainId = $message->body->train_id;
// Not sure what you want to do wit this ^
}
You need to loop over each whole entry. See how where the data is repeated, and that is what you need to loop over.
Your trying to access an array like an object. The array notation would be $data[0]['body'] to retrieve the value for the "body" key in the first entry in the array.

JSON format list of names - Symfony2

I'm trying to read a json file and parse it to an array, and then acces that array.
This is my JSON file:
{
"stijn",
"bert",
"tom"
}
This is how I try to acces it and convert it to an array:
$string = file_get_contents(__DIR__."/first.json");
$array = json_decode($string, true);
if I do a var_dump of $array I get "null", if I do it of $string I get the contents of the JSON file.
I think that my JSON file is not properly formatted, but if I search for some examples they are not suitable for my list of names.
you are right, your json is not formatted properly. you need to show that it is an array, so like this:
{
names: [
"stijn",
"bert",
"tom"
]
}
OR
[
"stijn",
"bert",
"tom"
]
notice that square brackets are used for an array. if you use the curly braces, it's looking for a key/value pair
What about ?
[
"stijn",
"bert",
"tom"
]

Categories