I know how to decode a JSON string with one object with your help from this example How to decode a JSON String
But now I would like to improve decoding JSON string with several objects and I can’t understand how to do it.
Here is an example:
{ "inbox": [
{ "firstName": "Brett", "lastName":"McLaughlin" },
{ "firstName": "Jason", "lastName":"Hunter" },
{ "firstName": "Elliotte", "lastName":"Harold" }
],
"sent": [
{ "firstName": "Isaac", "lastName": "Asimov" },
{ "firstName": "Tad", "lastName": "Williams" },
{ "firstName": "Frank", "lastName": "Peretti" }
],
"draft": [
{ "firstName": "Eric", "lastName": "Clapton" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff" }
]
}
- How to make just one foreach() to
decode above JSON string? - How to detect object’s names: inbox,
sent or draft on this foreach()?
New answer
Re your revised question:
foreachactually works with properties as well as with many-valued items (arrays), details here. So for instance, with the JSON string in your question:Within your main loop over the properties, you can use an inner loop to go over the array entries each property points to. So for instance, if you know that each of the top-level properties has an array value, and that each array entry has a “firstName” property, this code:
…will show:
Old answer(s)
Begin edit
Re your comment:
The example you posted does have several objects, they’re just all contained within one wrapper object. This is a requirement of JSON; you cannot (for example) do this:
That JSON is not valid. There has to be a single top-level object. It might just contain an array:
…or of course you can give the individual objects names:
End edit
Your example is one object containing three properties, the value of each of which is an array of objects. In fact, it’s not much different from the example in the question you linked (which also has an object with properties that have array values).
So: