0

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)
Jaurez
  • 3
  • 1
  • Please note that ChatGPT doesn't necessarily produce results that are 100% accurate – DarkKnight Jun 25 '23 at 15:24
  • [This might help](https://stackoverflow.com/questions/44794782/removing-a-new-line-feed-in-json-file-using-python) – Nesi Jun 25 '23 at 15:32

1 Answers1

0

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 ']'.

DarkKnight
  • 19,739
  • 3
  • 6
  • 22