Parse JSON & remove items in PHP - php

So, I have some JSON data that looks like this:
{
"Table1":[
{
"CURRENCY_FLAG":"EUR",
"TRADE_DATE":"2015-10-15",
"DELIVERY_DATE":"2015-10-15",
"DELIVERY_HOUR":"7",
"DELIVERY_INTERVAL":"1",
"RUN_TYPE":"EA",
"SMP":"35.370",
"LAMBDA":"35.370",
"SYSTEM_LOAD":"3164.611",
"CMS_TIME_STAMP":"2015-10-14T10:03:09+01:00"
},
{
"CURRENCY_FLAG":"GBP",
"TRADE_DATE":"2015-10-15",
"DELIVERY_DATE":"2015-10-15",
"DELIVERY_HOUR":"7",
"DELIVERY_INTERVAL":"1",
"RUN_TYPE":"EA",
"SMP":"26.460",
"LAMBDA":"26.460",
"SYSTEM_LOAD":"3164.611",
"CMS_TIME_STAMP":"2015-10-14T10:03:09+01:00"
}... etc
I'm pretty basic at PHP, but have fetched this data with CURL, and now I want to iterate through this data and remove every node with the "GBP" value for "CURRENCY_FLAG" and just hang onto those with the "EUR" sign.
Can anyone point me in the right direction of parsing this with PHP?
Thanks!

Try simply this way after decoding your json string using json_decode()
//decode json string
$result = json_decode($curl_result, true);
$final_result = [];
foreach($result['Table1'] as $key => $value){
if($value['CURRENCY_FLAG'] != 'GBP'){ //exclude currency flag with GBP
$final_result[] = $value;
}
}
print '<pre>';
print_r($final_result);
print '</pre>';

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.

how do i split my result using json

im using a text messaging service provider to send and receive messages. the following is the code that works successfully to retrieve messages from the texting server and displays on my website
the problem is when it displays this data its in one big chunk,sorry im not a great programmer therfore I want to split each text messages up by a few spaces,
please could you help me write up a json script that would allow me to split up my result, cheers
You need to decode the JSON from the string into an array or object, using json_decode() it has a second parameter that's bool (When TRUE, returned objects will be converted into associative arrays.)
So something like (Object):
$responseObj = json_decode($response);
foreach ( $responseObj as $key => $value )
echo "$key = $value<br>";
So something like (Array):
$responseArray = json_decode($response, true);
foreach ( $responseArray as $key => $value )
echo "$key = $value<br>";
first of all do use json_decode function of php then it will come up in an array where at "messages" index you can find your all messages. After that you have to run for each loop then you can get your code working.
$arr = json_decode($response, true);
foreach($arr['messages'] as $message){
echo $message['message'];
}
<?php
$response = json_decode($response);
foreach($response['messages'] as $msgObj) {
print $msgObj->message . "<br/><br/>";
}
?>

How to loop through this json decoded data in PHP?

I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);

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