Appending data to JSON file with python












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?










share|improve this question




















  • 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 8 at 20:41


















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?










share|improve this question




















  • 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 8 at 20:41
















1












1








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?










share|improve this question
















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?







python json python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 8 at 20:40









juanpa.arrivillaga

38k33672




38k33672










asked Nov 22 '18 at 22:09









PintSizedandCudddlyPintSizedandCudddly

83




83








  • 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 8 at 20:41
















  • 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 8 at 20:41










1




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 8 at 20:41







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 8 at 20:41














2 Answers
2






active

oldest

votes


















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.






share|improve this answer

































    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






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438505%2fappending-data-to-json-file-with-python%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      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.






      share|improve this answer






























        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.






        share|improve this answer




























          0












          0








          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 8 at 20:49

























          answered Jan 8 at 20:17









          buranburan

          1,284611




          1,284611

























              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






              share|improve this answer






























                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






                share|improve this answer




























                  0












                  0








                  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






                  share|improve this answer















                  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







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 8 at 22:53

























                  answered Jan 8 at 20:11









                  Mark CartagenaMark Cartagena

                  112




                  112






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438505%2fappending-data-to-json-file-with-python%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Wiesbaden

                      Marschland

                      Dieringhausen