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

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"}]

Related

JSON decode Array and insert in DB

I have some issue with a decoded Json object sended to a php file. I have tried some different format like this
{"2":"{Costo=13, ID=9, Durata_m=25, Descrizione=Servizio 9}","1":"{Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}"}
or this.
[{"Costo":"7.5","ID":"3","Durata_m":"30","Descrizione":"Barba Rasoio"},{"Costo":"4.5","ID":"4","Durata_m":"20","Descrizione":"Barba Macchinetta"}]
In order the first, any suggestions helps me, then i have converted previous string using GSON, however php doesn't decode.
This is my php:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data['servizi'] as $key => $value)
{ echo "Key: $key; Value: $value<br />\n";
}
How can I access single elements of array? What I'm doing wrong? Thanks in advance
I think you should check the content in this way
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
echo "FROM PHP: " . $value;
echo "Test : " .$value['ID'];
}
your elements of {Costo=7, ID=8, Durata_m=20, Descrizione=Servizio 8}
are not properly formated as an array element. That is a pure string and not an array value.
This is a json object with 1 element of array:
{
"1": {
"Costo": 7,
"ID": 8,
"Durata_m": 20
}
}
The Inside are json objects. Therefore your json string was not properly formated to operate with that logic. What you had was an element of a string. That is the reason why it was a valid json (passing jsonlint) but was not the correct one that you wanted to use.
UPDATE
Because this format is fix, I have a non-elegant way:
//Receive JSON
$JSON_Android = $_POST["JSON"];
//Decode Json
$data = json_decode($JSON_Android, true);
foreach ($data as $key => $value) {
//to separate each element
$newArray = explode(',',$value);
$newItem = explode('=', $newArray[1]);
echo "ID". $newItem[1];
}
That would be the dirty way to do it ONLY IF THE PLACEMENT OF DATA IS FIX. (ie the second element of the first explode is always ID.
I will leave it to someone else to make the suggested code better. I would recommend more to ensure that the json you are receive is proper because as I explained, it is incorrectly formated and as an api developer, you want an adaptive way for any given client to use the data efficiently.

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 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'].

Decode the String having same key

{"": "attachment-2","": "attachment-1"}
I am getting this JSON-encoded string (or an oher format... let me know) from parsing a mail and I can not change it. How can I decode it?
You cannot use a JSON parser for this as it will always overwrite the first element due to the same keys. The only proper solution would be asking whoever creates that "JSON" to fix his code to either use an array or an object with unique keys.
If that's not an option the only thing you can do it rewriting the JSON to have unique keys before parsing it using json_decode()
Assuming it always gives you proper JSON and the duplicate keys are always empty you can replace "": with "random-string": - preg_replace_callback() is your friend in this case:
$lame = '{"": "attachment-2","": "attachment-1"}';
$json = preg_replace_callback('/"":/', function($m) {
return '"' . uniqid() . '":';
}, $lame);
var_dump(json_decode($json));
Output:
object(stdClass)#1 (2) {
["5076bdf9c2567"]=>
string(12) "attachment-2"
["5076bdf9c25b5"]=>
string(12) "attachment-1"
}
This JSON response is invalid as #ThiefMaster mentioned, because JSON doesn't support duplicated keys.
You should contact the service you're trying to request this response from.
In case you have a valid JSON response you can decode it using the json_decode function
which returns an object or an array (depends on the second parameter);
For example: (Object)
$json_string = '{"keyOne": "attachment-2","keyTwo": "attachment-1"}';
$decoded = json_decode($json_string);
print $obj->keyOne; //attachment-2
print $obj->keyTwo; //attachment-1
Another option is to write your own decoder function.
Decode it yourself?
$myStr = '{"": "attachment-2","": "attachment-1"}';
$vars = explode(',',$myStr);
$arr = array();
foreach($vars as $v){
list($key,$value) = explode(':',$v);
$key = substr($key,strpos($key,'"'),strpos($key,'"')-strrpos($key,'"'));
$value = substr($value,strpos($value,'"'),strpos($value,'"')-strrpos($value,'"'));
if($key=='')$arr[] = $value;
else $arr[$key] = $value;
}

How to get individual fields from JSON in PHP

My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.

Categories