json_decode() expects parameter 1 to be string, array given? - php

this is my data ,After Json_encode()
Array
(
[{"customerId":"1","customer_name":"Jon_doe","amount":"12312312","billcode":"b1231","billname":"cashbilname","billcategorycode":"1234","billcategory":"utility","month":"May","year":"2015","txcode":"10","stationid":"152","station":"Coroom","operatorcode":"1200","operator":"jame","terminal":"ter12312","txdate":"12\/2\/2015","txtime":"12:21:22_PM"}]
=>
)
now i want to decode it back ,by applying json_decode() it gives the following error
json_decode() expects parameter 1 to be string, array given
any idea sugestion what to do ?

Your json must be in string, not in array
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$json_array = json_decode($json_string);
$json_array : ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
If your json is in array you can do :
$json_string_in_array = ['{"a":1,"b":2,"c":3,"d":4,"e":5}'];
$json_array = json_decode($json_string_in_array[0]);

json_encode() returns a string, so I don't know how you can be getting an array out of it unless you are storing it in an array yourself like:
$json = [];
$json[] = json_encode($someArray);
Instead, just store it in a non-array variable:
$jsonString = json_encode($someArray);
Then you can decode it like this:
$decodedArray = json_decode($jsonString);

$jsonstr = '[{"customerId":"1","customer_name":"Jon_doe","amount":"12312312","billcode":"b1231","billname":"cashbilname","billcategorycode":"1234","billcategory":"utility","month":"May","year":"2015","txcode":"10","stationid":"152","station":"Coroom","operatorcode":"1200","operator":"jame","terminal":"ter12312","txdate":"12\/2\/2015","txtime":"12:21:22_PM"}]';
$ar = json_decode($jsonstr,true); # json string to Array
$obj = json_decode($jsonstr); # json string to Object
var_dump($ar,$obj);

Related

how do I get my php array to json

I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);

PHP problems wiith decoding JSON

I have this data:
Array
(
[id] => 19936953
[name] => Zackaze
[profileIconId] => 585
[summonerLevel] => 30
[revisionDate] => 1394975422000
)
$str = json_decode($data,true);
$row = (object) $str;
echo $row['name'];
I tried this code but it constantly gives this error:
Fatal error: Cannot use object of type stdClass as array
Hopefully you can help me.
While the conversion to an object is unnecessary (as others have mentioned), that is not the cause of your error. You cannot access object properties using $array['key'] notation. You must use $object->property.
Alternatively, you can remove the $row = (object) $str; line, and then you can access $row as an array.
You already have decoded your json as an associative array since you used true as second parameter so you can print it directly with scopes. If you need to decode as an object simply remove the second parameter, I think you will need to access it in another way though.
$str = json_decode($data,true);
echo $str['name'];
The second argument of json_decode will convert the Object into a Associative Array. Just remove the second argument or change it to false and it will return a stdClass instead of a Associative array.
You can see the Documentation.
Try outputting like
$str = json_decode($data,true);
$str = array
(
'id' => 19936953,
'name' => Zackaze,
'profileIconId' => 585,
'summonerLevel' => 30,
'revisionDate' => 1394975422000
);
$row = (object) $str;
echo $row->name;
Or a cleaner way
$str = json_decode($data);
echo $str->name;

How can I fix this error about stdClass in PHP

This is my code:
$array = array(
"Birds" =>
array(
'group' => 1,
"Bird" => array(
array('id' => 1, 'img' => "img1.png", 'title' => "kate"),
array('id' => 2, 'img2' => "img2.png", 'title' => "mary")
)) );
$json = json_encode($array);
echo json_decode($json);
OUTPUT IS:
//JSON OUTPUT {"Birds":{"group":1,"Bird":[{"id":1,"img":"img1.png","title":"cardinal"},{"id":2,"img2":"img2.png","title":"bluejay"}]}}
Object of class stdClass could not be converted to string
try
var_dump($json);
This allows you to print out the details of objects and other non-primative types.
Echoing is used for strings - Your json decoded string will be an object of type stdClass
See var_dump http://php.net/manual/en/function.var-dump.php
See echo http://php.net/manual/en/function.echo.php
You have to pass the second parameter of json_decode as true, more info about these parameters at: http://php.net/manual/en/function.json-decode.php
so your echo json_decode($json); should be changed to this:
print_r(json_decode($json, true));
echo is changed to print_r since the output is an array not a string ...
Use var_dump to view variables echo converts your variable to string, while it's object. Also you can add second param to json_decode($data, true) to get array instead object, as i assume that's what you want, because input is array.
About object convertion to string you can read __toString

json_decode returns string type instead of object

I'm passing a JSON-encoded string to json_decode() and am expecting its output to be an object type, but am getting a string type instead. How can I return an object?
In the docs, the following returns an object:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
However, if I json_encode() the string first and then call json_decode(), the output is a string and not an object:
$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));
This is just a simplified example. In practice what I'm doing is pushing a JSON-encoded string to PHP via AJAX. However it does illustrate the problem of converting this encoded JSON string to an object I can read in PHP, e.g., "$json->a".
How can I return an object type?
thanks for the replies !
The actual context for this question was am using a JSON Response from a API.
But when I do the json_decode to this response and try to access the values like - $json=json_decode(json response from API);
echo $json->a
it gives me a error: Object of class stdClass could not be converted to string
The function json_encode is used to encode a native PHP object or array in JSON format.
For example, $json = json_encode($arr) where $arr is
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
);
would return the string $json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'. At this point, you do not need to encode it again with json_encode!
To obtain your array back, simply do json_decode($json, true).
If you omit the true from the call to json_decode you'll obtain an instance of stdClass instead, with the various properties specified in the JSON string.
For more references, see:
http://www.php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json, true));
http://hk.php.net/manual/en/function.json-decode.php
Instead of writing on the JSON array, try putting it into a PHP array first.
<?php
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5
);
//Then json_encode()
$json = json_encode($array);
echo $json;
die;
?>
In you case, you are using ajax. So when you get a success, you can do this:
$.ajax({
url: 'example.com',
data: {
},
success: function(data) {
console.log(data);
}
});
Where after data inside console.log() can add the json var like data.a, data.b...
Also, with the string you providedm you do not need to json_encode since it is alrady in json format
in your question you confused json_encode with and json_decode:
$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));
its should be:
$json = json_decode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_encode($json));

push array into multidimensional array?

I have json_encoded array that i would like to add to using php
[{"id":"a","value":"2"},{"id":"b","value":"2"}]
I want to add the following to the array above:
array("id" => c, "value" => "3")
I tried json_decode then trying to push the array into that but im confused on how to do that
Make sure you use json_decode in array mode rather than object mode:
// Default: JSON is decoded as object
$json_object = json_decode($json_string);
// Pass true in the second argument to get an array instead
$json_array = json_decode($json_string, true);
// Push a new entry onto the end
$json_array[] = array("id" => c, "value" => "3");
// Re-encode JSON string, if needed
$json_final_string = json_encode($json_array);

Categories