Jesús Cova
Jesús Cova

Reputation: 51

Issue creating a JSON

I have my code:

$data = array("apiKey" => "85526dd10b9aa01ae6e56698b848d191",
                    "turnos" => array("codigo" => '15918421', 
                    "nombreTurno" => "Uno", 
                    "inicio" => "01-12-2019", 
                    "termino" => "01-12-2019", 
                    "codigoImportacion" => "0"));

$data_string = json_encode($data);   

When I see how it looks like in JSON, it shows this:

{"apiKey":"85526dd10b9aa01ae6e56698b848d191","turnos":{"codigo":"15918421","nombreTurno":"Uno","inicio":"01-12-2019","termino":"01-12-2019","codigoImportacion":"0"}}

BUT it's wrong because I need this:

{"apiKey":"85526dd10b9aa01ae6e56698b848d191","turnos":["codigo":"15918421","nombreTurno":"Uno","inicio":"01-12-2019","termino":"01-12-2019","codigoImportacion":"0"]}

The problem is that I do not know how to put [] and not {}... turnos should be an array but it shows

"turnos":`{"codigo":"15918421","nombreTurno":"Uno","inicio":"01-12-2019","termino":"01-12-2019","codigoImportacion":"0"} and not "turnos":["codigo":"15918421","nombreTurno":"Uno","inicio":"01-12-2019","termino":"01-12-2019","codigoImportacion":"0"]

How can I make the change {} to []?

Upvotes: 0

Views: 45

Answers (2)

Mateusz Krawczyk
Mateusz Krawczyk

Reputation: 308

This JSON you said you need is not a valid JSON.

In JSON you can have object, which is made of pairs key-value

{"key1":"value1", "key2":"value2"}

or you can have array, which have only values

["value1", "value2", "value3", "value4"]

It could be confusing, because arrays in JSON are not exactly the same as arrays in PHP - associated arrays are serialized as objects.

Upvotes: 0

Yassine CHABLI
Yassine CHABLI

Reputation: 3744

The format you are looking for is wrong :

{ 
   "apiKey":"85526dd10b9aa01ae6e56698b848d191",
   "turnos":[ 
      "codigo":      "15918421",
      "nombreTurno":      "Uno",
      "inicio":      "01-12-2019",
      "termino":      "01-12-2019",
      "codigoImportacion":      "0"
   ]
}

I think your array should be something like :

$data = array("apiKey" => "85526dd10b9aa01ae6e56698b848d191",
                    "turnos" => [
                        ["codigo" => '15918421', 
                         "nombreTurno" => "Uno", 
                         "inicio" => "01-12-2019", 
                         "termino" => "01-12-2019", 
                         "codigoImportacion" => "0"]
                    ]
                    );

$data_string = json_encode($data);   

var_dump($data_string);

This will give you something like :

{ 
   "apiKey":"85526dd10b9aa01ae6e56698b848d191",
   "turnos":[ 
      { 
         "codigo":"15918421",
         "nombreTurno":"Uno",
         "inicio":"01-12-2019",
         "termino":"01-12-2019",
         "codigoImportacion":"0"
      }
   ]
}

Upvotes: 2

Related Questions