How do I print it into an organised json file?

谁说胖子不能爱 提交于 2019-12-12 04:53:47

问题


I need help with the output of my json file. I'm trying to print out the keys in a list called keypairs. I have to generate 60 keys, which i have included in the (count<60) part of my code (which isnt here). Im just showing the exporting part of my codes which i have a problem with. Here are my codes:

with open("/home/pi/Desktop/database.json", 'w+'):
    db = TinyDB('/home/pi/Desktop/database.json')
    table = db.table('Books')
    db.insert({'Book ID' : keypair[bookid], 'Serial No.' : keypair[bookserial] })

However, the problem I have right now is that it prints out all the keys in the lists - bookid and bookserial instead of printing a pair of keys in one { }.

Here's an example output where count<2:

Pillar": {}, "_default":
 {"1":
   {"Bookid": ["b'\\XXXXXX bookid 1 XXXXXXX'", "b'\\AAAAAA bookid 2 AAAAAAA'"], 
    "Serial No.": ["b'\\YYYYYserialno 1YYYYY'", "b'BBBBserial no2BBBB'"]
   }
 }

This is the output that i intend to get:

in a format like this where a pair of keys are printed everytime it runs again:

{ Books:
  {
    Book ID: XXXX bookid 1 XXXX
    Serial No.: XXX serialno 1 XXXX
  }
  {
    Book ID: XXX bookid 2 XXXX
    Serial No.: XXX serial no. 2 XXX
   }
 }

As you can see, the json file is messy, i have no idea how to make it automatically neat and also, you can see that the keys print out together into one instead of separately. Imagine having to print 60 pairs of these and they are all under one { }.

Help!


回答1:


I see multiple syntax problems in your code when you are trying to create the json. You could try to do this.

{ Books:
  {
      {
        Book ID: XXXXXXXX
        Serial No.: XXXXXXX
      },
      {
        Book ID: XXXXXXX
        Serial No.: XXXXXX
       }
  }
 }

As you can see i wrapped the book items in brackets as well and the items are comma separated now.

This could help you with your problem.



来源:https://stackoverflow.com/questions/44384527/how-do-i-print-it-into-an-organised-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!