你可以使用Python如何从JSON文件输出中删除空格和缩进?

huangapple go评论90阅读模式
英文:

How can I remove spaces and indentations from a JSON file output with Python?

问题

json.dump(extracted_data, file, separators=(',', ':'))
英文:

I have a Python script to extract data from one JSON file and put it into another:

import json

# Step 1: Read the JSON file
with open('input.json', 'r') as file:
    data = json.load(file)

# Step 2: Extract the specific data    
extracted_data = []

for token in data['tokens']:
    extracted_data.append({
        'symbol': token['symbol'],
        'address': token['address']
    })
    
# Step 3: Write the extracted data to a new JSON file
with open('output.json', 'w') as file:
    json.dump(extracted_data, file, indent=False)

This results in a JSON file formatted like this:

    {   
        "symbol": "4INT",
        "address": "0x5CEeBB0947d58Fabde2fc026Ffe4B33ccFE1bA8B"
    },
    {
        "symbol": "AAVE",
        "address": "0xD6DF932A45C0f255f85145f286eA0b292B21C90B"
    },
    {
        "symbol": "ACRE",
        "address": "0x011734f6Ed20E8D011d85Cf7894814B897420acf"
    },

But I want it to look like this:

    {"symbol": "4INT","address": "0x5CEeBB0947d58Fabde2fc026Ffe4B33ccFE1bA8B"},
    {"symbol": "AAVE","address": "0xD6DF932A45C0f255f85145f286eA0b292B21C90B"},
    {"symbol": "ACRE","address": "0x011734f6Ed20E8D011d85Cf7894814B897420acf"},

How can I do this?
I'm very new at coding and got the initial script from ChatGPT.

I tried:

json.dump(extracted_data, file, separators=(',', ':'))
json.dump(extracted_data, file, separators=(',', ':'), indent=None)
json.dump(extracted_data, file, separators=(',', ':'), indent=0)

答案1

得分: 0

你可以将输出文件写成如下方式:

with open('output.json', 'w') as o:
    items = ',\n'.join(map(json.dumps, extracted_data))
    o.write(f'[\n{items}\n]')

由于extracted_data是一个列表,我假设你想要在字典项周围添加[]

英文:

You could write your output file as follows:

with open('output.json', 'w') as o:
    items = ',\n'.join(map(json.dumps, extracted_data))
    o.write(f'[\n{items}\n]')

As extracted_data is a list I assume you'll want to wrap the dictionary items in '[' and ']'.

huangapple
  • 本文由 发表于 2023年6月25日 23:22:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551120.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定