RyanJP
RyanJP

Reputation: 287

php json example not working

Reading "PHP & jQuery Cookbook" right now and it gives this example for using json_decode()

<?php
$json = <<<JSON
{
  "origin":"Delhi",
  "destination":"London",
  "passengers":
  [
    {
      "name":"Mr. Perry Mason",
      "type":"Adult",
      "age":28
    }
    {
      "name":"Miss Irene Adler",
      "type":"Adult",
      "age":25
    }
  ],
  "travelDate":"17-Dec-2010"
}
JSON;

$objJson = json_decode($json);
echo ($objJson);

?>

The code just gives me a blank page when I run it. Is there something invalid about that JSON? Because json_decode() doesnt even seem to see it.

Upvotes: 0

Views: 656

Answers (5)

adamsmith
adamsmith

Reputation: 6009

First your JSON string is invalid, there is a comma missing between the two elements of "passengers".
Second, echo ($objJson) won't work, because Object of class stdClass could not be converted to string. You may use var_dump or print_r.

Upvotes: 0

Vigrond
Vigrond

Reputation: 8198

<?php
$json = <<<JSON
{
  "origin":"Delhi",
  "destination":"London",
  "passengers":
  [
    {
      "name":"Mr. Perry Mason",
      "type":"Adult",
      "age":28
    }**,**
    {
      "name":"Miss Irene Adler",
      "type":"Adult",
      "age":25
    }
  ],
  "travelDate":"17-Dec-2010"
}
JSON;

$objJson = json_decode($json);
**print_r** ($objJson);

?>

Upvotes: 0

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

rather use print_r() than using echo to see if it prints

but a comma is missing from your JSON input

it should be like this

 {
  "name":"Mr. Perry Mason",
  "type":"Adult",
  "age":28
},
{
  "name":"Miss Irene Adler",
  "type":"Adult",
  "age":25
}

Upvotes: 1

farzad
farzad

Reputation: 8855

you'r missing a comma after the closing bracket after "age":28} so your JSON should be:

<?php
$json = <<<JSON
{
  "origin":"Delhi",
  "destination":"London",
  "passengers":
  [
    {
      "name":"Mr. Perry Mason",
      "type":"Adult",
      "age":28
    },
    {
      "name":"Miss Irene Adler",
      "type":"Adult",
      "age":25
    }
  ],
  "travelDate":"17-Dec-2010"
}
JSON;

$objJson = json_decode($json);
echo ($objJson);

?>

Upvotes: 0

Ryan
Ryan

Reputation: 14649

Your JSON is invalid:

Parse error on line 9:
... "age": 28        }{            "name"
----------------------^
Expecting 'EOF', '}', ',', ']'

Your missing a comma in your passengers array.

<?php
$json = <<<JSON
{
  "origin":"Delhi",
  "destination":"London",
  "passengers":
  [
    {
      "name":"Mr. Perry Mason",
      "type":"Adult",
      "age":28
    },
{
  "name":"Miss Irene Adler",
  "type":"Adult",
  "age":25
}
  ],
  "travelDate":"17-Dec-2010"
}
JSON;

$objJson = json_decode($json);
echo ($objJson);

?>

Upvotes: 1

Related Questions