0

i have this json on which i try to extract the insertion-orders array

{
    "response" : {
        "status" : "OK",
        "count" : 1,
        "insertion-orders" : [{
                "id" : 5,
                "name" : "First Choice",
                "code" : null,
                "state" : "active",
                "line_items" : [{
                        "id" :352,
                        "timezone" : "Europe/London"
                    }, {
                        "id" :358,
                        "timezone" : "Europe/London"
                    }
                ],
                "labels" : null,
                "safety_pacing" : true
            }
        ]
    }
}

what im doing is TheJson is the json string:

$Json = json_decode($TheJson);
$JsonResponse = $Json->response;
$OrdersArray = $JsonResponse->insertion-orders;

the error im getting is :

Notice: Undefined property: stdClass::$insertion in /home/foo/a/foo.com/user/htdocs/FunctionManager.php on line 16

Notice: Use of undefined constant orders - assumed 'orders' in /home/foo/a/foo.com/user/htdocs/FunctionManager.php on line 16

line 16 is :

 $OrdersArray = $JsonResponse->insertion-orders;

i just don't get it , its valid json

2
  • But its not valid PHP Commented Jul 10, 2013 at 20:20
  • Use $JsonResponse->{'insertion-orders'} Commented Jul 10, 2013 at 20:22

1 Answer 1

2
$JsonResponse->insertion-orders;

is parsed as

$JSonResponse->insert MINUS orders

You can't use - in an object attribute name using the arrow notation. It'll have to be

$JsonResponse->{'insertion-orders'}

instead.

As for your comment about it being valid JSON, it wouldn't have worked in Javascript either:

json.insertion-orders 

will also be seen as json.insertion MINUS orders.

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

5 Comments

Are you allowed to use array notation with objects in PHP?
i think it would be possible to do $JsonResponse->{"insertion-orders"} but a better idea may be to pass true as the second argument to the json_decode and deal with it as an array.
Right. Brainfart on my part and mixing up JS/php. Edited the answer.
but in js it is valid to day json["insertion-orders"]
+1 for explaining why the original code fails, even though you were slow to post the right solution.

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.