Python格式化我的JSON输出[重复]

dtcbnfnu  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(70)

此问题在此处已有答案

I'm getting an IndentationError (or a TabError). How do I fix it?(6个答案)
How to prettyprint a JSON file?(15个回答)
18天前关闭.

# -*- coding: utf-8 -*-

import json
from pprint import pprint

drink_list = [23,601,633,673,607,662,6622,6014,6104,615,038,606,607,627,6094]

filename = (r'C:\Users\desktop\pizza\123template.json')

with open(filename, 'r') as f:
    data = f.read()

try:
    template = json.loads(data)
except Exception:
    # this file can also be here 
    print('json exception')
    raise

for output in drink_list:
    print(output)
    temp = template.copy()
    temp["meta"]["sodanumber"] = output

    with open(r'C:\Users\desktop\pizza\123\{}.json'.format(output, indent=40), 'w', encoding='cp1252') as f:
        data = json.dumps(temp)
        f.write(data)
       # pprint.pprint(temp, width=60)

IndentationError:未匹配任何外部缩进级别。
但我认为这不仅仅是一个简单的缩进。我可以让我的控制台更改格式,但需要在实际的输出文件中更改格式。但我在哪里添加额外的格式到我的“with open”行?
已经在这方面阅读了4个小时的材料,还有简单的例子,但是pprint做了大部分的工作吗?
当前的输出是大量的工作 Package 文本。输出需要看起来像下面。我如何才能让它看起来像这样?:

{
    "meta": {
        "drinkNumber": 662,
        "effectiveDate": "2016-10-12 16:00:31",
        "documentType": "checkout-device"
    },
    "documents": [
        {
            "code": "Checkout2",
            "name": "Printer 2",
            "port": "COM2",
            "type": "LABEL",


电流输出:

{ "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{
"code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL",

utugiqy6

utugiqy61#

import json

data = { "meta": { "drinkNumber": 662, "effectiveDate": "2016-10-12 16:00:31", "documentType": "checkout-device" },"documents": [{ "code": "Checkout2","name": "Printer 2","port": "COM2","type": "LABEL"}]}

json.dumps(data, sort_keys=True, indent=4)

字符串
输出量:

{
    "documents": [
        {
            "code": "Checkout2",
            "name": "Printer 2",
            "port": "COM2",
            "type": "LABEL"
        }
    ],
    "meta": {
        "documentType": "checkout-device",
        "drinkNumber": 662,
        "effectiveDate": "2016-10-12 16:00:31"
    }
}

注意:当前输出不完整。

相关问题