Seems like an easy thing, but I am not getting the expected data. I want to send an array of strings to my backend and then iterate/do stuff with them.
In the frontend I have:
var jsonArray = ["String1", "String2"]
await newFile(JSON.stringify(jsonArray));
In my controller, I have:
$requestData = json_decode($request->getContent(), true);
$this->logger->info("File request data is ", [ $requestData ]);
My logger outputs:
File request data is ["[\"String1\",\"String2\"]"]
Which is not an array, but a string.
If I do it inside of php with
$txt = ["Test", "Test2"];
$json = json_encode($txt, true);
print_r(json_decode($json));
The output would be an array. Where am I going wrong or what am I missing? Having the true option in json_decode should return me my array.
This
["Test", "Test2"]
is an Array, and this
"[\"String1\",\"String2\"]"
is a string. json_decode() need a string as parameter.
$jsonString = "[\"String1\",\"String2\"]";
$array = json_decode($jsonString, true);
var_dump($array);
/*
array(2) {
[0]=>
string(7) "String1"
[1]=>
string(7) "String2"
}
*/
Related
I have read a dozen stack posts on this topic and none of them work given my decoded JSON string. Here is my JSON:
{
"id":"cus_EfVGU7XtvtKUx2",
"account_balance":0,
"cards":{
"count":1,
"data":[
{
"id":"card_1ECAFn2H1YALOWTjH0zGfOS7",
"exp_month":11,
"exp_year":2019,
"last4":"1111",
"metadata":[
],
"name":"ned land",
"type":"Visa"
}
]
},
"invoice_prefix":"5F8A134",
"has_more":false,
"total_count":1,
"url":"\/v1\/customers\/cus_EfVGU7XtvtKUx2\/sources"
}
Then I encode that string into an object:
$obj = json_decode($json, false);
I can easily get that top-most id value by doing this:
$obj->id
But when I try to get the exp_month value, I get back an empty string:
$expMonth = $obj->cards->data->exp_month;
Then alternatively I try array syntax:
$obj = json_decode($json, true);
$expMonth = $obj["cards"]["data"]["exp_month"];
And again $expMonth resolves to an empty string. What am I doing wrong?
Use $expMonth = $obj->cards->data[0]->exp_month;. $data is an array.
Full example:
$obj = json_decode('{
"id":"cus_EfVGU7XtvtKUx2",
"account_balance":0,
"cards":{
"count":1,
"data":[
{
"id":"card_1ECAFn2H1YALOWTjH0zGfOS7",
"exp_month":11,
"exp_year":2019,
"last4":"1111",
"metadata":[
],
"name":"ned land",
"type":"Visa"
}
]
},
"invoice_prefix":"5F8A134",
"has_more":false,
"total_count":1,
"url":"\/v1\/customers\/cus_EfVGU7XtvtKUx2\/sources"
}');
print_r($obj->cards->data[0]->exp_month);
Output is 11.
data is an array of objects.
$obj->cards->data[0]->exp_month
should do the job
I'm trying to read the returned json below but i keep getting errors.
Cannot use object of type stdClass as array
I'm fetching the json via curl and then json_decode($data);
foreach($array as $a)
{
switch($a)
{
case"BTC":
//do something
case"ETH":
//do something
}
}
Url :
https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,LTC,XMR,XRP,DASH,ZEC&tsyms=USD
Var Dump Results :
object(stdClass)#405 (6) { ["BTC"]=> object(stdClass)#404 (1) { ["USD"]=> float(13571.4) } ["LTC"]=> object(stdClass)#406 (1) { ["USD"]=> float(235.57) } ["XMR"]=> object(stdClass)#407 (1) { ["USD"]=> float(399.11) } ["XRP"]=> object(stdClass)#408 (1) { ["USD"]=> float(1.83) } ["DASH"]=> object(stdClass)#409 (1) { ["USD"]=> float(1000.25) } ["ZEC"]=> object(stdClass)#410 (1) { ["USD"]=> float(658.29) } }
Decode as Associative Array
For decoding JSON as an array, you have to pass assoc parameter to the json_decode function.
When the assoc parameter is TRUE, returned objects will be converted into associative arrays.
Refer PHP Docs for more information regarding the function.
Example Code
json_decode($data, true);
There is a second parameter to json_decode which allows you to parse json data as associative arrays.
try:
json_decode($data, true);
I have this json code:
$cars = '{
"CarBenz":
[
{
"Car": "Benz",
"Color": "Black"
}
]
}';
$json = json_decode($cars , true);
how to print Benz in screen?
print $json['Car'];
$json['Car'] nothing show anything.
To see the type of a variable (and how an object or array is built up) you can use var_dump($json).
In this case, that will give:
array(1) {
["CarBenz"]=>
array(1) {
[0]=>
array(2) {
["Car"]=>
string(4) "Benz"
["Color"]=>
string(5) "Black"
}
}
}
So you need to do $json['CarBenz'][0]['Car'].
First you can var_dump your decoded json string and you can see the array with the structure.
I think you forgot to access the CarBenz element first.
echo $json['CarBenz'][0]['Car'];
If you need all elements in CarBenz you have to iterate over them. Something like that:
foreach($json['CarBenz'] as $car) {
echo $car;
}
I have this jsone that I need to convert in three different objects.
in some php. I know that i have to use json_decode but I only decode the first object , the others 2 object don't.
{
"recorrido":[
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:32",
"globaltime":"00:09",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":1,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
},
{
"lon":"-60.67216873168769",
"lat":"-32.9230105876913",
"date":"13/10/24-12:22:35",
"globaltime":"00:12",
"globalkm":0.0,
"speed":2.11,
"altitude":-32.9230105876913,
"groupId3":0,
"id":2,
"color":0,
"auxInt":0,
"groupId2":0,
"provider":1,
"groupId1":0,
"workoutid":1
}
],
"user":{
"asunto":"",
"userId":1
},
"Itemout":{
"uploaded":"false",
"isSelected":false,
"id":1,
}
}
what do you sugest? the script must be in php. the object "recorrido" is a multiple array object.
wthout testing it, try somrting like this:
$tempArray = (array)$recorrido; // or how you cal your json object
foreach ($tempArray as $tempJson)
{
$myArray = json_decode($tempJson);
print_r($myArray);
}
You can use hardcode method if you have static json structure:
Show below
$result = json_decode($json);
$recorrido = $result->recorrido;
// And so on
In another way there is a workaround with arrays.
list($arr1, $arr2, $arr3) = json_decode($json, true);
This solution will make you three arrays of data from json.
I have a model that sends an error response to the controller in CodeIgniter that then is passed to the view which is just a JSON encoder. Here is the array from the model.
return $posts[] = array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
The issue I am having is that I need those square brackets after the $posts variable because sometimes I need an array of errors. However when I pass the single array to the view it encodes the JSON without the square brackets but when I have multiple arrays it includes the square brackets, I need the square brackets in the JSON every time. Here is the Controller...
$data['data'] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Here is the view...
header('Content-type: application/json');
$response['response'] = $data;
echo json_encode($response);
I need the JSON response to look like this
{
"response": [
{
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
]
}
NOT THIS!
{
"response": {
"complete": 0,
"error": 1003,
"message": "Username already exists"
}
}
Since you want to get array in json you should be having it in php array as well (i.e. data-structures should meet). So $response['response'] = $data; should be $response['response'] = array($data);
In your example var_dump($response); gives:
array(1) {
["response"]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
As you see $response['response'] is an object for json.
When you replace $response['response'] = $data; with $response['response'] = array($data); your data-structure, which you want to convert in json will become:
array(1) {
["response"]=>
array(1) {
[0]=>
array(3) {
["complete"]=>
int(0)
["error"]=>
int(1003)
["message"]=>
string(23) "Username already exists"
}
}
}
That will give you desired output because json_encode will expect that there might be another items in $response['response'].
Demo
Edit
Your model should be returning one dimensional array. For example:
return array('complete'=>0,'error'=>1003, 'message'=>'Username already exists');
And you should assign it to another array that is holding all error messages:
$data['data'][] = $this->logins_model->signup($post_data);
$this->load->view('json', $data);
Demo 2
In your view define $post as an array and remove tha square brackets from there. To check your results in view use print_r instead of echo. Which will show exactly how many data is retrieved.