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.
Related
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"}]
Okay, so I think you get what I wanna do by just watching the code.
//Get JSON text file (Steam API)
$json = file_get_contents('http://store.steampowered.com/api/appdetails?appids=57690');
//Decode JSON
$game_json = json_decode($json, true);
//Target game name and echo it
echo $game_json['name'];
The JSON itself comes in this order (unstructured, very sorry):
{"57690":{"success":true,"data":{"type":"game","name":"Tropico 4: Steam Special Edition"
So my target is ""name":"Tropico 4: Steam Special Edition"", which is what I want to echo on my page. I'm not sure if it helps, but "name": appears once, is something like [0] needed in my code to target the first? Is the nesting what's stopping me here, or is the $game_json['name']; an incorrect way of targeting?
ANY tips and/or help will be much appreciated. Thanks.
In the future, use print_r($game_json) to check the array structure.
<?php
$json = file_get_contents('http://store.steampowered.com/api/appdetails?appids=57690');
$game_json = json_decode($json, true);
echo $game_json['57690']['data']['name'];
//Tropico 4: Steam Special Edition
echo $game_json['57690']['data']['required_age'];
//0
//etc...
<?php
//This is your json string
$string = {"57690":{"success":true,"data":{"type":"game","name":"Tropico 4: Steam Special Edition"...
//Turn JSON string into object
$data = json_decode($string);
//Turn your object into an array (easier to work with in this case)
$data = (Array)$data;
//Get name of item with "57690" key
$name = $data["57690"]->data->name;
//Echo the name
echo($name);
//You can also echo out all names of all items like this:
foreach($data as $key => $item)
{
echo($item->data->name);
}
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>';
{"": "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;
}
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.