How do I print it into an organised json file?

2019-09-14 22:29发布

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条回答
Summer. ? 凉城
2楼-- · 2019-09-14 23:35

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.

查看更多
登录 后发表回答