Decoding Nested JSON in PHP - 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.

Related

Extracting one object/group out of a JSON array and save it to a new file using PHP. I am hung up on the array part of the code

I have the following json structure I am trying to loop through and extract products from:
[]JSON
->{0}
-->[]username
-->[]avatar
-->[]rep
-->[]products
-->[]groups
-->[]feedbacks
-->[]online
-->[]staff
I am trying to ave only the products object into as a JSON file. This is the only result I need and delete/unset the rest:
[]JSON
->{0}
-->[]products
But I seem to be a bit confused, as I am not to familiar with how arrays work around PHP. Here is an angle I am currently trying:
<?php
$str = file_get_contents('test.json');
$json_decoded = json_decode($str,true);
foreach($json_decoded as $index){
unset($json_decoded[$index][???]);
}
file_put_contents('cleaned.json', json_encode($json_decoded));
?>
I added ??? where I am lost, this is about as far as I have gotten. I keep getting super confused. I know the structure will always be the same as above so I can technically just remove username,avatar,rep,groups,feedbacks,online, and staff seperatly. Which is just fine.
Here is an example of the json structure:
[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]
Thank you in advance, even a push in the right direction is much appreciated.
You could compose a new products array like this :
$products = [];
foreach($json_data as $value) {
$products[]['products'] = $value['products'];
}
file_put_contents('cleaned.json', json_encode($products));
This will results json objects like this :
[
{
"products": ["Big-01"]
},
{
"products": ["Big-02"]
},
{
"products": ["Big-03"]
},
{
"products": ["Big-04"]
},
{
"products": ["Big-05"]
}
]
From your snippet. try this.
<?php
$str = '[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]';
$json_decoded = json_decode($str,true);
foreach($json_decoded as $value) {
$products = $value['products'];
}
print_r( $products);
?>
output
Array
(
[0] => Big
)
Create a new array ($products), iterate over the old array, and set products as the one property instead of unseting every single array.
$products = [];
foreach ($json_decoded as $index) {
$products[$index] = [
'products' => $json_decoded[$index]['products']
];
}
file_put_contents('cleaned.json', json_encode($products));

Get JSON Data From .json (php)

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D
{
"status": 300,
"data": {
"date": "2019-09-16T00:00:00.000Z",
"featured": [
{
"name": "Flying Saucer",
"price": "1,200",
"images": {
"icon": icon.png",
},
"rarity": "epic",
},
I'm using this that a friend told me, but i cant put that to work :c
<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {
$item = $val['name'];
echo "<b>$item</b>";
}
?>
I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:
echo $response['status']; // would output 300
You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:
foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
echo $val['featured']['name'];
}
You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.
When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.
I suggest you to read about json_decode and json in general:
JSON: https://www.json.org/
json_decode function: https://www.php.net/manual/en/function.json-decode.php

How to parse a file with a multiple JSONs in PHP(Laravel)?

I have input file that looks something like this:
{"name": "foo"}{"name": "bar"}
How to parse that?
If you're sure, that the individual JSONs are valid, you can try to transform it into an array of JSON objects, like this:
$data = '{"name": "foo"}{"name": "bar"}';
$data = str_replace('}{', '},{', $data);
$data = '[' . $data . ']';
// Now it's valid
// [{"name": "foo"},{"name": "bar"}]
Since }{ is always invalid in JSON, it's safe to say, that it won't affect your data.
there are several way to parse json objects such as this .. but you must know the exact structure of that object ..
one way is to iterate each child ..
foreach($jsonObj as $obj)
{
// access my name using
$obj->name;
$obj->someotherfield
// or iterate again .. assuming each object has many more attribute
foreach($obj as $key => $val)
{
//access my key using
$key
// access my value using
$val
}
}
there are tons of other ways to do that so .. and also , a valid json is like [{"name": "foo"},{"name": "bar"}]

PHP JSON getting specific value of each key

I have a php code that reads JSON files. Part of the JSON sample below:
"Main": [{
"count": 7,
"coordinates": [89,77],
"description": "Office",
},{
"count": 8,
"coordinates": [123,111],
"description": "Warehouse",
}]
and I am trying to code PHP to only get the info (count, coordinates, description) of those who's description is included in the criteria like Warehouse. PHP Sample below
$validcriteria = array("Warehouse", "Parking_lot");
How do I do an if-statement to check first if "description" is included in the valid criteria. I tried the code below but it doesn't seem to work right.
$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
if (in_array($key['description'] , $validcriteria))
{
#more codes here
}
}
My code in PHP has been working except when I try to add $key['description'] to try and check the description first if it's valid. My code above is reconstructed to remove sensitive information but I hope you got some idea of what I was trying to do.
When attempting to understand the structure of a parsed JSON string, start with a print_r($JSONFile); to examine its contents. In your case, you will find that there is an outer key 'Main' which holds an array of sub-arrays. You will need to iterate over that outer array.
// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value['description'], $validcriteria))
{
// Do what you need to with it...
}
}
Note: if you prefer to continue setting the $assoc parameter to false in json_decode(), examine the structure to understand how the objects lay out, and use the -> operator instead of array keys.
$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value->description, $validcriteria))
{
// Do what you need to with it...
}
}
You might also consider using array_filter() to do the test:
$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria
Given your JSON structure, you probably want
foreach($decoded_json['Main'] as $sub_array) {
if (in_array($sub_array['description'], $validation)) {
... it's there ...
}
}
Because you set false to second argument of json_decode function, it's returned as an object,
if you change it to TRUE, the code would work.
http://php.net/manual/en/function.json-decode.php
and you have to change key to value;
foreach ($JSONFile->Main as $key => $value)
{
if (in_array($value->description, $validcriteria))
{
#more codes here
}
}
this code assume your json file has one more depth greater than your example. that's why $JSONFile->Main in the foreach loop.
Try to use that :
if ( array_key_exists('description', $key) )

JSON PHP Querying

I have a question about querying JSON structures that make use of nested objects. In order to explain, I will use some examples.
For Examples Sake, the variable $json is a JSON file:
movies [{"name":"good movie", "poster":"link"}]
Normally after I've used the json_decode() function on a JSON file I can do something like
$newFiles = $json["movies"];
foreach ($newFiles as $file) {
$name = $file["name"]; }
But, lets say I have this JSON File:
movies[{"name":"good movie", "poster": {"original":"link", "smaller":"link"}}]
How would I get the value of "original", I've tried doing something like:
$newFiles = $json["movies"];
foreach ($newFiles as $file) {
$poster = $file["poster" -> "original"]; }
That, however, doesn't work. I can't find the appropriate syntax to query this. Any help appreciated, thanks in advance!
When you decode your json with json_decode(), set the second parameter to true, as so:
<?php
$movies = '[{"name":"good movie", "poster": {"original":"link", "smaller":"link"}}]';
$movieArray = json_decode($movies,true);
foreach($movieArray as $movie){
print_r($movie['poster']['original']);
}
?>
This will allow you to convert returned objects into associative arrays. Therefore it is possible to do something like $movie['poster']['original'].

Categories