I have the following JSON String
{
"name":"Product",
"properties":
{
"id":
{
"type":"number",
"description":"Product identifier",
"required":true
},
"name":
{
"type":"string",
"description":"Name of the product",
"required":true
},
"price":
{
"type":"number",
"minimum":0,
"required":true
},
"tags":
{
"type":"array",
"items":
{
"type":"string"
}
},
"stock":
{
"type":"object",
"properties":
{
"warehouse":
{
"type":"number"
},
"retail":
{
"type":"number"
}
}
}
}
}
I would like to access
properties - > stock - > properties - > warehouse.
In python I can do the following.
f = open("c:/dir/jsondec.json")
data = json.load(f)
node = data['properties']['stock']['properties']['warehouse']
print str(node)
I’m trying to do the same thing in PHP. I know I can use json_decode() but what should be the correct syntax.
Also If I have an array within say within properties-> ID I could have done ['properties'][0]['id'] to access that. What would be the equivalent in php?
Version in Python
This is in Python:
Version in PHP
And this is its equivalent in PHP:
“Gotchas” (or “slight differences”)
There is one difference however:
fin Python version is opened file, while$fin PHP version is already a string.As RPM correctly noted, there is another difference: arrays in PHP are converted to string “
Array” when used in string context (see here: http://ideone.com/XJfSP), so you probably would like to use:or
instead of
to see the actual content of the array.
EDIT: Changed
json_decode()result into array.