exequielc
exequielc

Reputation: 701

Parse JSON Array Objetct into PHP script

A have to send this Json Array from Android to a php script. In this case I've send this json with 1 element ('CABECERA') and in my php script I don't know how to parse to work with.

How I have to do to re-create an entire CABECERA object from this json?.

 $_jsone_str= [ {\"CABECERA\":[{\"CustomerID\":\"1\",\"datetime\":\"\",\"fecha\":\"150303122830\",\"idadmin\":\"3\",\"idcli\":\"4\",\"msj\":\"\",\"nroped\":\"\",\"orderId\":\"1\",\"puntoVentaID\":\"AMALGAME\",\"status\":\"0\",\"total\":\"0.0\"}]}]

$json = json_decode($_jsone_str);

foreach ( $json ->CABECERA as $decode ){
   print_r($decode);
}

How supose to parse this json array what I do wrong?

Upvotes: 0

Views: 308

Answers (3)

What I usually do is the following:

  1. I first check if POST JSON with POST HEADER POST exists:

    if( isset($_POST["POST"]) ) {
    
    }
    
  2. I deallocate the JSON file:

    $data = $_POST["JSON"];
    $data = stripslashes($data);
    $jsonDecoded = json_decode($data);
    
  3. I then parse the JSON data:

    foreach ($jsonDecoded->**"object/array name"** as $object) {
    
    }
    

In your case, "object/array name" happens to be CABECERA

Full code:

if( isset($_POST["JSON"]) ) {

    $data = $_POST["JSON"];
    $data = stripslashes($data);
    $jsonDecoded = json_decode($data);

    foreach ($jsonDecoded->**"object/array name"** as $object) {

    }
}

Upvotes: 1

feskr
feskr

Reputation: 829

Make sure JSON to be decoded is a string:

$_jsone_str= "[ {\"CABECERA\":[{\"CustomerID\":\"1\",\"datetime\":\"\",\"fecha\":\"150303122830\",\"idadmin\":\"3\",\"idcli\":\"4\",\"msj\":\"\",\"nroped\":\"\",\"orderId\":\"1\",\"puntoVentaID\":\"AMALGAME\",\"status\":\"0\",\"total\":\"0.0\"}]}]";

$json = json_decode($_jsone_str);

Check the result:

print_r($json);

Call it the right way:

foreach ( $json as $decode ){
   print_r($decode->CABECERA);
}

Upvotes: 0

Codew
Codew

Reputation: 494

The json array must be a string.

And the function json_decode($data, true) - Lookup for the second paremeter, it will return the parsed json in associative arrays else it will be as object.

    $json = "[ {\"CABECERA\":[{\"CustomerID\":\"1\",\"datetime\":\"\",\"fecha\":\"150303122830\",\"idadmin\":\"3\",\"idcli\":\"4\",\"msj\":\"\",\"nroped\":\"\",\"orderId\":\"1\",\"puntoVentaID\":\"AMALGAME\",\"status\":\"0\",\"total\":\"0.0\"}]}]";

foreach ( json_decode($json, true) as $decode ){
   print_r($decode);
}

Upvotes: 0

Related Questions