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

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

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

问题

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

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

  1. import json
  2. # Step 1: Read the JSON file
  3. with open('input.json', 'r') as file:
  4. data = json.load(file)
  5. # Step 2: Extract the specific data
  6. extracted_data = []
  7. for token in data['tokens']:
  8. extracted_data.append({
  9. 'symbol': token['symbol'],
  10. 'address': token['address']
  11. })
  12. # Step 3: Write the extracted data to a new JSON file
  13. with open('output.json', 'w') as file:
  14. json.dump(extracted_data, file, indent=False)

This results in a JSON file formatted like this:

  1. {
  2. "symbol": "4INT",
  3. "address": "0x5CEeBB0947d58Fabde2fc026Ffe4B33ccFE1bA8B"
  4. },
  5. {
  6. "symbol": "AAVE",
  7. "address": "0xD6DF932A45C0f255f85145f286eA0b292B21C90B"
  8. },
  9. {
  10. "symbol": "ACRE",
  11. "address": "0x011734f6Ed20E8D011d85Cf7894814B897420acf"
  12. },

But I want it to look like this:

  1. {"symbol": "4INT","address": "0x5CEeBB0947d58Fabde2fc026Ffe4B33ccFE1bA8B"},
  2. {"symbol": "AAVE","address": "0xD6DF932A45C0f255f85145f286eA0b292B21C90B"},
  3. {"symbol": "ACRE","address": "0x011734f6Ed20E8D011d85Cf7894814B897420acf"},

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

I tried:

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

答案1

得分: 0

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

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

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

英文:

You could write your output file as follows:

  1. with open('output.json', 'w') as o:
  2. items = ',\n'.join(map(json.dumps, extracted_data))
  3. 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:

确定