1

I have written the following python code to populate a JSON file.

import json

data = {}  
data['people'] = []

for i in range(0,3):
    data['people'].append({
    'name': 'C%d'%(i),
    'div':i,
    'from': 'City%d'%(i)
})

with open('data.txt', 'w') as outfile:  
    json.dump(data, outfile)

However, my JSON file looks something like this:

{"people": [{"div":0,"from":,"City0":"name":"C0"},{"div":0,"from":,"City0":"name":"C0"}]}

My order of input is different from the output's. What is the reason and how do I rectify this?

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 1
    What order? Do you mean the order of the keys in your objects? Why should it matter to you? AFAIK, according to the JSON spec, objects are inherently unordered, and you certainly shouldn't be relying on any particular order. If you *do* care about order, use a JSON array – juanpa.arrivillaga Jan 08 '19 at 20:41

2 Answers2

0

The reason your output is like that is because json files don't really care what order they are in, they hold data and are used in comparison with a file directory. As long as you can get to the file and it actually be the file, its all good. You more or less want it to be exactly how you input it which would be impossible with json.dumps, If you absolutely need it that way, Id just make a string like
string='''{"people": [{#arange in order you want it}]}'''
and save it how you would any other file.

If your looking to sort your json, try something i found here Sorting Json

0

What python version do you use? You create a dict, but before python 3.6 order of insertion is not preserved. In python 3.6 order of insertion is preserved, but it's considered implementation detail and should not be relied upon. In python 3.7 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. If you are using python version lower than 3.7 use OrderedDict from collections.

import json
from collections import OrderedDict

data = {}
data['people'] = []
for i in range(0,3):
    data['people'].append(OrderedDict((
    ('name', 'C%d' %(i)),
    ('div', i),
    ('from', 'City%d'%(i))
    )))

with open('data.json', 'w') as outfile:  
    json.dump(data, outfile)

By the way, why the extension of the file is txt and not json? It doesn't matter and is not related to your problem, but I am curious.

buran
  • 13,682
  • 10
  • 36
  • 61