PHP JSON decode - stdClass - php

I was having a question about making a 2D JSON string
Now I would like to know why I can't access the following:
$json_str = '{"urls":["http://example.com/001.jpg","http://example.com/003.jpg","http://example.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';
$j_string_decoded = json_decode($json_str);
// echo print_r($j_string_decoded); // OK
// test get url from second item
echo j_string_decoded['urls'][1];
// Fatal error: Cannot use object of type stdClass as array

You are accessing it with array-like syntax:
echo j_string_decoded['urls'][1];
Whereas object is returned.
Convert it to array by specifying second argument to true:
$j_string_decoded = json_decode($json_str, true);
Making it:
$json_str = '{"urls":["http://site.com/001.jpg","http://site.com/003.jpg","http://site.com/002.jpg"],"alts":["testing int chars àèéìòóù stop","second description",""],"favs":["true", "false", "false"]}';
$j_string_decoded = json_decode($json_str, true);
echo j_string_decoded['urls'][1];
Or Try this:
$j_string_decoded->urls[1]
Notice the -> operator used for objects.
Quoting from Docs:
Returns the value encoded in json in
appropriate PHP type. Values true,
false and null (case-insensitive) are
returned as TRUE, FALSE and NULL
respectively. NULL is returned if the
json cannot be decoded or if the
encoded data is deeper than the
recursion limit.
http://php.net/manual/en/function.json-decode.php

json_decode by default turns JSON dictionaries into PHP objects, so you would access your value as $j_string_decoded->urls[1]
Or you could pass an additional argument as json_decode($json_str,true) to have it return associative arrays, which would then be compatible with $j_string_decoded['urls'][1]

Use:
json_decode($jsonstring, true);
to return an array.

Related

PHP parse multidimensional array with json

I'm trying to parse a json string extracted from a MySQL database. The json string contains a two-dimensional array, but json_decode returns null and json_last_error returns 0 which I assume means no error occurred.
$result is the json string
json_decode($result, true);
The string:
[
["17544500374","17544500489","17544500571","17544500587","17544500528"],
["17544500651","17544500432","17544500673","17544500452","17544500362"],
["17544500454","17544500457","17544500523","17544500441"],
["17544500547","17544500463","17544500535","17544500676"],
["17544500548","17544500581","17544500584","17544500382"],
["17544500593","17544500364","17544500660","17544500595"],
["17544500635","17544500647","17544500529","17544500670"]
]
You do not have a key for your values. That means, your second parameter is not correct, because the function is unable to create an associative array.
This works fine on my mashine:
json_decode($result);
The $result must be a string:
$result = '[["17544500374","17544500489","17544500571","17544500587","17544500528"],["17544500651","17544500432","17544500673","17544500452","17544500362"],["17544500454","17544500457","17544500523","17544500441"],["17544500547","17544500463","17544500535","17544500676"],["17544500548","17544500581","17544500584","17544500382"],["17544500593","17544500364","17544500660","17544500595"],["17544500635","17544500647","17544500529","17544500670"]]'

Query and decode json form mysql database

I have this JSON encoded code in my mysql database:
{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}
And i want to query and decode it to echo it at my website.
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 = '{"Suggestion":{"Title":"Casinos","Text":"maybe it will be good if its there casinos "},"ID":6,"VoteNo":[],"Status":"Voting","Player":{"SteamID":"STEAM_0:1:36988062","Name":"Pepi"},"Approved":{"Name":"Nido Johnson","Is":true,"SteamID":"STEAM_0:0:47457253"},"VoteYes":{"1":"STEAM_0:0:56939043","2":"STEAM_0:0:55948188","3":"STEAM_0:1:25856984","4":"STEAM_0:1:40894071"}}';
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.
/ 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 <br/>";
foreach($value as $k=>$data)
{
echo "$k | $data <br/>";
}
}

Get the value for key in json array in php

How to get the corresponding value for key associated
[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]
Your Json is valid. 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 = '[{"name":"challenge","properties":[{"name":"mobileNo","value":"aa"},{"name":"challengeT","value":"1Day"},{"name":"emailId","value":"ff#gmail.com"},{"name":"deviceId","value":"9500e297-081b-4f97-93b7-dafddc55db31"}]},{"name":"challenge","properties":[{"name":"emailId","value":"a#b.com"},{"name":"mobileNo","value":"345345"},{"name":"deviceId","value":"435435dfgdfg"}]}]' ;
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 <br/>";
foreach ($value as $key2 => $value2) {
echo "$key2 = $value2 <br />";
}
}
Output :
0
name = challenge
properties = Array
1
name = challenge
properties = Array

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));

PHP json_encode return rows as objects instead of arrays [duplicate]

This question already has answers here:
json_encode/json_decode - returns stdClass instead of Array in PHP
(7 answers)
Closed 9 years ago.
I am using json_encode() to encode array into json format. but it returning object instead of array. I want to return an array not an object.
any body have any idea?
Basically json_decode() will return two types of data.
1) Object
2) Associative array
By default, json_decode() returns object type value.
But, if you want value as an array format you must use TRUE as a second argument in json_decode().
e.g,
$decoded_value = json_decode($json_encoded_value, TRUE);
use this code for decoding your encode json data
$encode = $your_json_encoded_data
json_decode($encode, TRUE);
actually json_encode function in php will return a json formatted string.
and if you want to parse json formatted string back in php
then you should use json_decode.
json_decode function will return data two types.
object & associtavie array.
json_decode(); return type object
json_decode(, TRUE); return type associtative array
You should use json_decode with TRUE param like following example:
$array = array(1,2,3);
$encode = json_encode($array);
$decode = json_decode($encode, TRUE);
Now $decode is array, not object.

Categories