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.
Related
I want to add data to existing JSON file
JSON:
{
"s1":[
{
"bID":"q4a4xs",
"bName":"Package1",
"bStep":"slast"
},
{
"bID":"q4a4xs",
"bName":"Package2",
"bStep":"s2"
}
],
"s2":[
{
"bID":"q4a4xs",
"bName":"Package15",
"bStep":"slast"
}
]
}
I want to create data for s3
What I did?
$newdata = ['bID' => 'O4bt2xs','bName' => 'Package91','bStep' => 's1'];
$newBox = 's3';
$encDexJSON = json_decode($json);
array_push($encDexJSON->{$newBox}->{$newdata}, $newdata);
Print:
{
"s1":[
{
"bID":"q4a4xs",
"bName":"Package1",
"bStep":"slast"
},
{
"bID":"q4a4xs",
"bName":"Package2",
"bStep":"s2"
}
],
"s2":[
{
"bID":"q4a4xs",
"bName":"Package15",
"bStep":"slast"
}
],
"w3":{
"Array":null
}
}
Where is the problem?
To be fair, the code you provided along with the given data wouldn't even give that result. However, it's obvious that you are doing a great number of things wrong here.
For starter's you're trying to call an array on object property, which makes no sense $encDexJSON->{$newBox}->{$newdata}. That literally translates to $encDexJSON->s3->['bID' => 'O4bt2xs','bName' => 'Package91','bStep' => 's1'] which obviously makes no sense at all.
Furthermore, array_push does not do what you want here. array_push is for arrays. What you want to do is simply assign a value to a specific object property. So just do so.
$encDexJSON->$newBox = [$newdata];
Now if you wanted to simply push new objects into that array...
$encDexJSON->$newBox[] = $newdata; // this pushes value onto end of array
The array_push equivalent would be...
$encDexJSON->$newBox = [];
array_push($encDexJSON->$newBox, $newdata); // same result as above
The use of array_push tends to get in the way. It's usually cleaner just to stick to the syntax above.
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 have a array of various object, but I need turn this objects into unique object. Below I share my code.
$result = [];
$idiomas = Idioma::all()->toArray();
foreach ($idiomas as $lang) {
$result[] = [
$lang['palavra_chave'] => $lang[$id]
];
}
return response()->json($result);
reponse
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
But I need transform this objects into one, like this
[
{
"INICIAL": "Inicial",
"RELATORIOS": "Relatórios",
"FUNCIONARIO": "Funcionário",
"DATA": "Data",
"ANEXAR_IMAGEM": "Anexar imagem",
"DISCIPLINA": "Disciplina"
}
]
anyone can help me?
$idiomas = Idioma::all()->toArray();
if (count($idiomas)) {
//$result = new stdClass; # wouldn't work without base namespace
$result = new \stdClass;
foreach ($idiomas as $lang) {
$result->{$lang['palavra_chave']} = $lang[$id];
}
return response()->json([$result]);
}
// otherwise
Edit: #Tpojka's answer definitely looks more appropriate. Use the following one only if you can't change the way you retrieve data initially (I'm not familiar enough with Laravel).
The following should work:
// Take your initial JSON
$input = <<<JSON
[
{ "INICIAL": "Inicial"},{ "RELATORIOS": "Relatórios"},{ "FUNCIONARIO": "Funcionário"},{ "DATA": "Data"},{ "ANEXAR_IMAGEM": "Anexar imagem"},{ "DISCIPLINA": "Disciplina"}
]
JSON;
// Transform it into a PHP array
$input_as_array = json_decode($input);
// Reduce it into an associative array
$associative_array = array_reduce($input_as_array, function($associative_array, $item) {
return $associative_array += (array)$item;
}, []);
// Encode it back into JSON, as an array
$result = json_encode([$associative_array], JSON_PRETTY_PRINT);
json_encode converts an object to:
{
"height":10,
"width":20,
"depth":5
}
But I need it to include the objects class name as well:
{
"cuboid":
{
"height":10,
"width":20,
"depth":5
}
}
public function toJson() {
return json_encode([get_class($this) => $this]);
}
Hope this will help you out. Here we are converting json to array and putting it into an array of field cuboid
Try this code snippet here
<?php
ini_set('display_errors', 1);
$json='{
"height":10,
"width":20,
"depth":5
}';
$result["cuboid"]=json_decode($json,true);
echo json_encode($result,JSON_PRETTY_PRINT);
You can use get_class to get class name of an object.
$json = json_encode(array(get_class($object) => $object));
Rules for json_encode
if you have an object it will be encode to {'pro1':'value'}
if you have an array it will be encode to ['value']
if you have an string it will be encode to 'value'
Note: If you have an assoc-array in php, it becomes an object in json! If you have an index-array it will be an array in json. Dont mix index & assoc!
Test this bad pratice: echo json_encode(array('foo' => 'bar',1,2)); Result is this bad syntax {"kitten":"test","0":1,"1":2} (propertie-names should NOT be numbers !!!)
So if you want and object under a property name do this
$obj = new stdClass();
$obj->prop = array(1,2,'a');
$newObject = new stdClass();
$newObject->objname = $obj;
print_r(json_encode($newObject));
Becomes: {'objname':{'prop':[1,2,'a']}}
Have a nice day :-)
I need to iterate some JSON formatted data into loop using PHP. My JSON data is below:
{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}
I need to run the loop so that the result data will come in above format using PHP.
Convert the php object to json object using json_encode
// convert object => json
$json = json_encode($myObject);
This might helpful: https://stackoverflow.com/a/9858457/6285410
What you showed us is a Possible JSON Data. In this Format, we can do nothing with it in PHP except by decoding back into Native PHP Object. Once that is done, You can access all the Properties of the Object like you do with normal PHP Object like $objData->questin1. Here's what is meant with the above statements:
<?php
$strJson = '{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}';
$objData = json_decode($strJson);
var_dump($objData);
// NOW, TO GET AT EACH OF THE PROPERTIES OF THE OBJECT IS EASY...
// ACCESS THE question1 OR question2
$q1 = $objData->question1;
$q2 = $objData->question2;
// ACCESS THE que WITHIN question 1 OR question2
$k1 = $objData->question1->ques; // EQUIVALENT TO: $q1->ques
$k2 = $objData->question2->ques; // EQUIVALENT TO: $q2->ques
// ACCESS THE optional ARRAY INSIDE OF question 1 OR question2
$opt1 = $objData->question1->optional; // EQUIVALENT TO: $q1->optional
$opt2 = $objData->question2->optional; // EQUIVALENT TO: $q2->optional
var_dump($q1, $q2, $k1, $k2, $opt1, $opt2);
?>