Decode the String having same key - php

{"": "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;
}

Related

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

Decode JSON post data

My php file receives a post from ajax call. The string received by the php file is as follows :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
I am trying unsuccessfully to decode this string then loop through the values in the array. I have tried the following :
$myarray =json_decode($_POST["userid"],true);
foreach ($myarray as $value) {
//do something with value
}
I am not sure whether the decode is the issue or my syntax to loop through the PHP array.
The POST data you'd want to manipulate is stored in $_POST['userid]
In case you're trying to access this comma separated user ids, you need to convert this to an array first using explode(). And then loop through these id's.
if (isset($_POST)) {
$user_ids = $_POST['userid']; // assssssss,camo,castor
$user_id_arr = explode(',', $user_ids); // Converts string to array Array (0 => assssssss, 1 => camo, 2 => castor)
foreach ($user_id_arr as $user_id) {
//Statements
}
}
$_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. So when you decode with json_decode that will decode JSON string to Object/Array.
But in your scenario you have not passed JSON String to $_POST so it not looks decoding.
The string you have passed into your $_POST is not JSON, so json_decode will not work on some random comma seperated values.
You can either pass in real JSON, or just use the explode method of splitting these values:
// explode example
$users = "assssssss,camo,castor";
$usersarray = explode(",", $users);

Parse JSON & remove items in 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>';

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.

Processing Multidimensional JSON Array with PHP

This is the json that deepbit.net returns for my Bitcoin Miner worker. I'm trying to access the workers array and loop through to print the stats for my myemail#gmail.com worker. I can access the confirmed_reward, hashrate, ipa, and payout_history, but i'm having trouble formatting and outputting the workers array.
{
"confirmed_reward":0.11895358,
"hashrate":236.66666667,
"ipa":true,
"payout_history":0.6,
"workers":
{
"myemail#gmail.com":
{
"alive":false,
"shares":20044,
"stales":51
}
}
}
Thank you for your help :)
I assume you've decoded the string you gave with json_decode method, like...
$data = json_decode($json_string, TRUE);
To access the stats for the particular worker, just use...
$worker_stats = $data['workers']['myemail#gmail.com'];
To check whether it's alive, for example, you go with...
$is_alive = $worker_stats['alive'];
It's really that simple. )
You can use json_decode to get an associative array from the JSON string.
In your example it would look something like:
$json = 'get yo JSON';
$array = json_decode($json, true); // The `true` says to parse the JSON into an array,
// instead of an object.
foreach($array['workers']['myemail#gmail.com'] as $stat => $value) {
// Do what you want with the stats
echo "$stat: $value<br>";
}
Why don't you use json_decode.
You pass the string and it returns an object/array that you will use easily than the string directly.
To be more precise :
<?php
$aJson = json_decode('{"confirmed_reward":0.11895358,"hashrate":236.66666667,"ipa":true,"payout_history":0.6,"workers":{"myemail#gmail.com":{"alive":false,"shares":20044,"stales":51}}}');
$aJson['workers']['myemail#gmail.com']; // here's what you want!
?>
$result = json_decode($json, true); // true to return associative arrays
// instead of objects
var_dump($result['workers']['myemail#gmail.com']);

Categories