Python格式化我的json输出

时间:2018-08-08 18:45:01

标签: python json formatting output pprint

# -*- 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:unindent与任何外部缩进级别都不匹配。

但是我认为这不仅仅是一个简单的缩进。我可以让控制台更改格式,但是需要在实际的输出文件中更改格式。但是,我应该在“打开”行中添加其他格式吗?

已经阅读了4个小时的材料以及简单的示例,但是pprint是否完成了大部分工作?

当前输出是大量的工作包装文本。输出如下所示。我怎样才能使它看起来像这样?:

{
    "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",

1 个答案:

答案 0 :(得分:1)

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

注意:您当前的输出不完整。