1

I'm trying to parse the following Json file:

{
"Itineraries" : [{
            "date1" : "20/Jan/2016",
            "date2" : "20/Jan/1996",
            "Options" : [
                {
                    "Num_ID" : [398],
                    "Quotedwhen" : today,
                    "Price" : 330.00
                }
            ]
        }
    ]

}

I'm using the following PHP code:

$json2 = file_get_contents("data.json");
var_dump(json_decode($json2));
$parsed_json2 = json_decode($json2);
$price = $parsed_json2->{'Itineraries'}->{'Options'}->{'Price'};

And I get the following error (Line 35 is the last line of the PHP code above):

Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/jsonread.php on line 35

Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/jsonread.php on line 35

Do you have any idea of how to solve this problem?

3
  • 1
    1. It's not valid JSON: jsonlint.com Commented Nov 2, 2016 at 21:01
  • 2. It would be $parsed_json2->Itineraries[0]->Options[0]->Price Commented Nov 2, 2016 at 21:03
  • Yes, that worked. Thanks Commented Nov 2, 2016 at 21:31

2 Answers 2

2

You have to put the string

today

In double qoutes

"today"

Because its a string :)

Sign up to request clarification or add additional context in comments.

Comments

0

the reason you are getting that message is because the json_decode() is failing to return an object because your JSON is invalid. You need to put double quotes around today. You are also accessing the data incorrectly.

Here's the correct code to get the price:

echo($parsed_json2->Itineraries[0]->Options[0]->Price);

You have created a lot of arrays here which only have one item in them, are you intending to have multiple itinerary, multiple options objects, and multiple Num_IDs per options object? If not you can get rid of a lot of those square brackets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.