Assign JSON values to simple variables

Asked

Viewed 2,612 times

0

I’m having trouble reading a JSON I receive:

{"data":{"charges":{"data":{"charges":[{"code":10006756,"dueDate":"13/09/2014","link":"https://www.teste.com.br"}]},"success":true}

I need to assign these values to my variables, this array will always have 1 record, it’s a rule.

How to get all of his variables (code, dueData, link and success) and assign these values to simple variables? That is in my code I will have:

$code  = valordoJSON;
$dueData    = valordoJSON;
$link  = valordoJSON;
$sucesso    = valordoJSON;

2 answers

6

You can use the function json_decode. This function receives a String in JSON format and returns a object or array with the properties of JSON.

Follow a very simple example:

$json = '{"nome": "Bruno", "sobrenome": "da Silva", "idade": "37"}';

//transforma o JSON em um objeto
$objeto = json_decode($json);

echo 'Nome: ' . $objeto->nome;
echo 'Sobrenome: ' . $objeto->sobrenome;
echo 'Idade: ' . $objeto->idade;

If you don’t want an object, you can turn JSON into a array, passing by true as the second function parameter:

$json = '{"nome": "Bruno", "sobrenome": "da Silva", "idade": "37"}';

//transforma o JSON em um array
$array = json_decode($json, true);

echo 'Nome: ' . $array['nome'];
echo 'Sobrenome: ' . $array['sobrenome'];
echo 'Idade: ' . $array['idade'];

0

it seems that the part {"data":{"charges":{"data":{"charges" is duplicated outside that:

<?php
$obj = json_decode('{"data":{"charges":[{"code":10006756,"dueDate":"13/09/2014","link":"https://www.teste.com.br"}]},"success":true}');

$code  = $obj->data->charges[0]->code;
$dueData = $obj->data->charges[0]->dueDate;
$link = $obj->data->charges[0]->link;
$sucess = $obj->success;

echo $code;
echo $dueData;
echo $link;
echo $sucess;
?>
  • 1

    A multidimensional array can repeat keys, see: {"id":[{"id":2, "a":"1", "b":"2"}]}, the result is: array(id=>array(0=>array(id=>2,a=>1,b=>2)))

  • yes, but in his example it seems to be repeated, for the first two {"data":{"charges": are not closed

  • I know, but the example you used gives the impression that there would be a collision in case of keys with the same name - I made just one observation because it changed the array. The json of the question is wrong even, seems to have been written manually.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.