Reputation: 41
Which of the following two examples is considered a better format for JSON - in terms of convention, standards and/or saving memory (or for any other reason)?
Thank you in advance.
Example 1:
{ "items": [ { "position": "Programmer", "age": 29, "fname": "Bob" }, { "position": "Developer", "age": 24, "fname": "Joe" }, { "position": "DBA", "age": 31, "fname": "Dave" }, { "position": "Systems", "age": 40, "fname": "Cindy" }, { "position": "Designer", "age": 32, "fname": "Erin" }, { "position": "NWA", "age": 45, "fname": "Sam" }, { "position": "Processor", "age": 20, "fname": "Lenny" }, { "position": "Webmaster", "age": 28, "fname": "Ed" } ] }Example 2:
{ "position": [ "Programmer", "Developer", "DBA", "Systems", "Designer", "NWA", "Processor", "Webmaster" ], "age": [ 29, 24, 31, 40, 32, 45, 20, 28 ], "fname": [ "Bob", "Joe", "Dave", "Cindy", "Erin", "Sam", "Lenny", "Ed" ] }
Upvotes: 1
Views: 364
Reputation: 298076
Definitely 1.
You can iterate over it logically in any language:
for person in json['items']: # 'people'?
print person['name']
You will have to convert 2 into 1 if you want to iterate over it:
data = [{key: json[key][i] for key in json} for i in range(len(json.keys()[0]))]
Also, GZip compression helps reduce the overhead of the duplicate keys (I stripped out the whitespace):
File | Size (b) | Gzipped Size (b)
----------------------------------
1 | 191 | 176
2 | 386 | 196
Upvotes: 2
Reputation: 8540
The first is much cleaner, in my opinion. It groups the attributes of each person together, which lends itself well to converting into a Person object. Iteration and sorting are also easier when there is only a single list, and for sorting Python provides attrgetter for simple sort keys. Technically, the second might be more efficient due to fewer dictionaries, but clarity beats any tiny gain from that.
Upvotes: 3