如何将其打印到有组织的json文件中? [英] How do I print it into an organised json file?

查看:95
本文介绍了如何将其打印到有组织的json文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有关json文件输出的帮助.我正在尝试打印出称为密钥对的列表中的密钥.我必须生成60个键,这些键已包含在我的代码的(count< 60)部分中(此处未提供).我只是显示我有问题的代码的导出部分.这是我的代码:

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] })

但是,我现在遇到的问题是,它打印出列表中的所有键-bookid和bookerial,而不是在一个{}中打印一对键.

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 { }.

这是一个示例输出,其中count< 2:

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
   }
 }

如您所见,json文件杂乱无章,我不知道如何使它自动整齐,而且,您还可以看到键一起打印出来,而不是分开打印.想象一下,必须打印60对,它们都在{}以下.

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 { }.

帮助!

推荐答案

当您尝试创建json时,我在您的代码中看到了多个语法问题.您可以尝试执行此操作.

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.

这篇关于如何将其打印到有组织的json文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆