unable to decode json variable - php

I have following piece of code which is generating JSON variable. I use php built in json_decode function to decode the json variable but i am getting NULL after decoding JSOn variable.
$a=array("targetAction"=>"getHeadFields","targetHead"=>$table_name);
$obj1 = Post_Uamsdata($a);
echo $obj1;
$file = json_decode($obj1,true);
var_dump($file);
$obj1 is my json variable. whenever i echo it i get the result as follows:
{"success":"yes","error":"","message":"","arguments":"[{\"fieldNo\":\"1\",\"fieldName\":\"ItemType\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"2\",\"fieldName\":\"Long\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"3\",\"fieldName\":\"Lat\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"4\",\"fieldName\":\"MapDate\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"5\",\"fieldName\":\"FieldNote\",\"fieldType\":\"character(64)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]}]"}
i have checked it in online json validator and it is saying that this JSOn is valid. But whenever i decode this $obj1 into $file then i am always getting NULL.

after json_decode we get the following, But I guess this is not what you want. You want the fieldNo, fieldName etc also to be parsed.
$json = '{"success":"yes","error":"","message":"","arguments":"[{\"fieldNo\":\"1\",\"fieldName\":\"ItemType\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"2\",\"fieldName\":\"Long\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"3\",\"fieldName\":\"Lat\",\"fieldType\":\"character(20)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"4\",\"fieldName\":\"MapDate\",\"fieldType\":\"character(16)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]},{\"fieldNo\":\"5\",\"fieldName\":\"FieldNote\",\"fieldType\":\"character(64)\",\"notnull\":\"f\",\"fieldLabel\":null,\"primary_key\":\"f\",\"default\":null,\"fieldOption\":[]}]"}';
$arr = json_decode($json, true);
echo "<pre>";
print_r($arr);
Output is as follows
Array
(
[success] => yes
[error] =>
[message] =>
[arguments] => [{"fieldNo":"1","fieldName":"ItemType","fieldType":"character(16)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"2","fieldName":"Long","fieldType":"character(20)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"3","fieldName":"Lat","fieldType":"character(20)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"4","fieldName":"MapDate","fieldType":"character(16)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]},{"fieldNo":"5","fieldName":"FieldNote","fieldType":"character(64)","notnull":"f","fieldLabel":null,"primary_key":"f","default":null,"fieldOption":[]}]
)

As http://php.net/manual/en/function.json-decode.php indicates that the function will only work for UTF-8 encoded string, try the following:
$file = json_decode(mb_convert_encoding($obj1, 'UTF-8'),true);

Related

How to insert an array in a json object in PHP

I have a string on my databas, that I'm trying to insert into a json object as an Array, not a string..:
$arrayInString = "[2,3,5,5,6]"; // this comes from the database
$jsonObject = array('numbers' => $arrayInString);
$json = json_encode($jsonObject, JSON_UNESCAPED_SLASHES);
echo $json;
When I execute this.. my Json object is..
numbers: "[2,3,5,5,6]";
and not
numbers: [2,3,5,5,6];
Like I originally wanted.. can't get this to work, can anyone help?
Like was said you need to decode the passed data from the database and then build your array output. Something like this:
$arrayInString = "[2,3,5,5,6]"; // this comes from the database
// decode the JSON from the database as we build the array that will be converted back to json
$jsonObject = array('numbers' => json_decode($arrayInString));
echo json_encode($jsonObject, JSON_UNESCAPED_SLASHES);
The slightly modified code above outputs:
{"numbers":[2,3,5,5,6]}
You need to json_decode your $arrayInString variable before you add it to the associative array.

get data from json array in php

I am having trouble accessing information in a json-Array that I retrieved using php's json_decode function.
the json-file looks as follows:
{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":XXX,"currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}
I used the following php code to get the contents:
$json = file_get_contents($json_url);
$data = json_decode($json,true);
echo '<pre>' . print_r($json, true) . '</pre>';
The result print_r displays looks just like what I expect and looks like the json.
However, I cannot figure out to access the variables. Whenever I try something like
$test = $json['model']['results']['balance'];
the script throws an error, which I can't identify. I already figured out if I access the $json variable like so:
$test = $json[n]; // returns the nth character, e.g. n = 0 $test = "{", n = 2 $test = "c"
The script also did not throw an error if I tried accessing the variable like so:
$test = $json['code']; // returns "{"
Can someone help me figure out how to navigate this array?
Thanks!
The results key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data, not the $json string.
This should work for you:
$test = $data['model']['results'][0]['balance'];
This is what should have tipped you off:
{"results":[{"message"
^ ^
| |
| \-- Start of an array
|
\-- Start of an object
You recieve an error similar to Cannot use object of type stdClass as array in (...) right?
json_decode returns an object of the type stdClass which is the only object in php (as far as I know) which properties cannot be accessed like an array. You will have to access them as follows:
$json = '{"code":0,"message":"Okay","model":{"results":[{"message":"Okay","balance":0,"openPositions":[[],[]],"firstDepositDate":"XX","currencySign":"€","email":"X.X#X.com","code":0}]},"result":"success"}';
$obj = json_decode($json);
var_dump($obj->message); //works
var_dump($obj["message"]); //throws exception
There is an error in the JSON array. "firstDepositDate": XXX is not a valid value. Should be a string "XXX".
Also you are trying to the wrong variable. The decoded data should be a PHP array. In this case $data['code'] instead of $json['code']

PHP read file (array) as array

How can I read a json array and add/merge a new element to it?
The content of my file data.json looks like this array:
[["2015-11-24 18:54:28",177],["2015-11-24 19:54:28",178]]
new element array example:
Array ( [0] => Array ( [0] => 2015-11-24 20:54:28 [1] => 177 ) )
I used explode() and file() but it failed (delimiter for index 1..)..
has someone another idea or it is the right way to solve?
Firstly you need to import JSON content to your application as a string what can be done with file_get_contents().
After that you have to decode--or "translate"--JSON format to PHP primitives via json_decode(). The result will be the expected array to be handled.
Then you may append a new item to that array using [] suffix eg. $a[] = $b;
These three steps are exemplified below.
// get raw json content
$json = file_get_contents('data.json');
// translate raw json to php array
$array = json_decode($json);
// insert a new item to the array
$array[] = array('2015-11-24 20:54:28', 177);
In order to update the original file you have to encode PHP primitives to JSON via json_encode() and can write the result to desired file via file_put_contents().
// translate php array to raw json
$json = json_encode($array);
// update file
file_put_contents('data.json', $json);
<?php
$c = file_get_contents('data.json');
// <- add error handling here
$data = json_decode($c, true);
// <- add error handling here, see http://docs.php.net/function.libxml-get-errors
see http://docs.php.net/file_get_contents and http://docs.php.net/json_decode

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

JSON decode with PHP: Key started with # sign

JSON is like
{
"#http_status_code": 200,
"#records_count": 200,
"warnings": [],
"query": { ... ...
In PHP
$data = json_decode($json_entry);
print $data->#http_status_code; //returns error
print $data->http_status_code; //returns nothing
How can I retrieve status code?
1) As Object way
$data = json_decode($json_entry);
print $data->{'#http_status_code'};
2) OR use as array way by passing second argument as true in json_decode
$data = json_decode($json_entry, true);
print $data['#http_status_code'];
Try json_decode to get the json in form of array ..
$json_array = json_decode($data, true);
$required_data = $data['required_key']
with reference to your particular problem .. you will get array as
Array
(
[#http_status_code] => 200
[#records_count] => 200
[warnings] => Array
(
)
....
)
so you can access you data as $data['#http_status_code']
To access an object property that has funky characters in the name, quote the name and stick it in braces.
print $data->{'#http_status_code'};
Or, say $data = json_decode($json_entry, true); to get the data back as an array.
PHP cwill give syntax error when you do this:
$data->#http_status_code;
it looks for $http_status_code variable which is not present
so in order to make this work you have to do this:
echo $data->{'#http_status_code'};
Try this:
$data = json_decode($json_entry, true);
print $data["#http_status_code"];

Categories