英文:
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 ']'.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论