Error reading JSON with PHP

Asked

Viewed 327 times

2

I am trying to read a JSON file in php with the following format:

{"leads":
  [{"id":"1",
    "email":"[email protected]",
    "user": "[email protected]",
    "first_conversion": {
      "content": {
        "identificador":"ebook-abc",
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "conversion_origin": {
            "source": "source 1",
          }
    },
    "last_conversion": {
      "content": {
        "identificador":"webinar-abc",
        "email_lead":"[email protected]"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "cumulative_sum":"2",
    },
    "custom_fields": {
        "Destino": "EUA"
      },
    "website": "http://www.site.com.br",
    "mobile_phone":"48 30252598",
    "city":"Sao Paulo",
    "state": "SP",
    "tags": ["tag 1", "tag 2"],
  }]
}

I tried returning the results in php in 2 formats. The first as follows:

$request = file_get_contents('php://input');
$input = json_decode($request, true);
$id = $input['leads']['nome'];
echo $id;

And the second form using foreach:

$request = file_get_contents('php://input');
$input = json_decode($request, true);
$lead = $input->leads;
foreach($lead as $result){
   echo "ID: ". $result->id;
}

Neither way is returning a result. Can anyone help me and tell me where I’m going wrong?! Thanks :D

3 answers

3


There are some mistakes in your json what makes the PHP return null when you use the json_decode, errors are the commas in the last elements of each objeto, for example:

"conversion_origin": {
    "source": "source 1",
}


"last_conversion": {
    "content": {
        "identificador": "webinar-abc",
        "email_lead": "[email protected]"
    },
    "created_at": "2012-06-04T15:31:35-03:00",
    "cumulative_sum": "2", // <-- virgula ao final
},

To check whether the json is valid, you can use the Jsonlint.

The last element of a list cannot contain a comma in json

Also, see also that the leads is a array, this way you need to inform the number of the Index to access it as array and as object, see:

// Utilizando array
$json = json_decode($raw, true);
var_dump($json['leads'][0]['id']); // Saida: string(1) "1"

// Utilizando objeto
$obj = json_decode($raw);
var_dump($obj->leads[0]->id); // Saida: string(1) "1"

Using an iteration

foreach($obj->leads as $lead) {
   echo $lead->id;
}

OR:

foreach($json['leads'] as $lead) {
    echo $lead['id'];
}

3

I downloaded your code and tested here, at least the error I identified was that following the format of your json is giving error in the comma in the last items of your list.

Ex: (wrong)

$json = '{
      "id":[{
          "nome":"nome de teste",
          "sobrenome": "sobrenome aqui", //no caso do json a última virgula no último item não deve existir
      }]
}';

Ex: (correct)

$json = '{
      "id":[{
          "nome":"nome de teste",
          "sobrenome": "sobrenome aqui" //vírgula removida
      }]
}';

I tested its format with these modifications I mentioned above.

$json = '{
    "leads":[{"id":"1",
    "email":"[email protected]",
    "user": "[email protected]",
    "first_conversion": {
      "content": {
        "identificador":"ebook-abc"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "conversion_origin": {
            "source": "source 1"
          }
    },
    "last_conversion": {
      "content": {
        "identificador":"webinar-abc",
        "email_lead":"[email protected]"
      },
      "created_at":"2012-06-04T15:31:35-03:00",
      "cumulative_sum":"2"
    },
    "custom_fields": {
        "Destino": "EUA"
      },
    "website": "http://www.site.com.br",
    "mobile_phone":"48 30252598",
    "city":"Sao Paulo",
    "state": "SP",
    "tags": ["tag 1", "tag 2"]
  }]
}';

$converte = json_decode($json, true);
print_r($converte);

2

Your code is correct. The error is in the json content.

The last element of a list cannot contain a comma in json as in PHP. If you use the block below, you will see that your first code works perfectly.

{"leads": [
    {
        "id": "1",
        "email": "[email protected]",
        "user": "[email protected]",
        "first_conversion": {
            "content": {
                "identificador": "ebook-abc"
            },
            "created_at": "2012-06-04T15:31:35-03:00",
            "conversion_origin": {
                "source": "source 1"
            }
        },
        "last_conversion": {
            "content": {
                "identificador": "webinar-abc",
                "email_lead": "[email protected]"
            },
            "created_at": "2012-06-04T15:31:35-03:00",
            "cumulative_sum": "2"
        },
        "custom_fields": {
            "Destino": "EUA"
        },
        "website": "http://www.site.com.br",
        "mobile_phone": "48 30252598",
        "city": "Sao Paulo",
        "state": "SP",
        "tags": [
            "tag 1",
            "tag 2"
        ]
    }
]}

Browser other questions tagged

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