I have the following JSON file as input,
{
"$type": "NanoWebInterpreter.WebInputData, NanoWebInterpreter",
"NBBList": {
"$type": "System.Collections.Generic.List`1[[monoTNP.Common.NBB, monoTNP.Common]], mscorlib",
"$values": [
{
"$type": "monoTNP.Common.NBB, monoTNP.Common",
"ID": "id-0065-00000003",
"MPList": {
"$type": "System.Collections.Generic.List`1[[monoTNP.Common.MP, monoTNP.Common]], mscorlib",
"$values": [
{
"$type": "monoTNP.Common.EllipticalMP, monoTNP.Common",
"Eccentricity": 1.0,
"ID": "id-0065-00000006",
"ParticleIndex": -1,
"DispersionInteractionStrength": 0.0,
"DispersionInteractionRange": 2.5,
"CharacteristicSize": 0.0,
"CenterOfMass": "<0,0,0>",
"OrientationVector": "<>"
},
{
"$type": "monoTNP.Common.CubeMP, monoTNP.Common",
"ID": "id-0065-00000005",
"ParticleIndex": -1,
"DispersionInteractionStrength": 0.0,
"DispersionInteractionRange": 2.5,
"CharacteristicSize": 0.0,
"CenterOfMass": "<0,0,0>",
"OrientationVector": "<>"
},
{
"$type": "monoTNP.Common.CircularMP, monoTNP.Common",
"ID": "id-0065-00000004",
"ParticleIndex": -1,
"DispersionInteractionStrength": 0.0,
"DispersionInteractionRange": 2.5,
"CharacteristicSize": 0.0,
"CenterOfMass": "<0,0,0>",
"OrientationVector": "<>"
}
]
},
etc.
My ultimate goal is to trace this tree recursively, wrapping each key/object name with <ul>
tags, and the properties at the "ParticleIndex" level in some kind of <form>
structure, but I can't figure out how to index into the two '$values' arrays.
This is the code that I have been manipulating to learn how each element(object or array) is accessed:
foreach ($json->NBBList->'$values'[0] as $key => $value){
var_dump($key);
echo "\n".var_dump($value);
echo "\n\n\n";
}
This obviously doesn't work because the index of values is outside of the string, but when it is on the inside, PHP interprets it as part of the string.
Is there a way for me to index into each element of the '$values' array, and ultimately in a for loop?
I'm thinking using the "true" property of JSON decode might be a better solution...
You can access object properties with names that contain special characters using this notation:
$json->NBBList->{'$values'}[0]
I don't think that this behavior is documented anywhere, but you can find it in the PHP grammar (see definition of variable_name
, which is used in object_dim_list
, which is used in object_property
).
Set the assoc
parameter of json_decode
to false to get arrays(dictionaries) instead of objects:
$json = json_decode($jsonInput, true);
foreach ($json['NBBList']['$values'][0] as $key => $value){
var_dump($key);
echo "\n";
var_dump($value);
echo "\n\n\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With