How can I make my json file a valid json file with Python

Viewed 61

I am new to Python, my Json file looks like this:

[
    {
        "Symbol": "TCS",
        "Series": "EQ",
        "Date": "04-May-2020",
        "Prev Close": 2014.45,
        "Open Price": 1966.0,
        "High Price": 1966.0,
        "Low Price": 1913.65,
        "Last Price": 1930.5,
        "Close Price": 1930.45,
        "Average Price": 1939.3,
        "Total Traded Quantity": 3729409.0,
        "Turnover": 7232442404.05,
        "No. of Trades": 165528.0,
        "Deliverable Qty": 1752041.0,
        "% Dly Qt to Traded Qty": 46.98
    }
]

it should be like this

{ 


"tcs":[
    {
        "Symbol": "TCS",
        "Series": "EQ",
        "Date": "04-May-2020",
        "Prev Close": 2014.45,
        "Open Price": 1966.0,
        "High Price": 1966.0,
        "Low Price": 1913.65,
        "Last Price": 1930.5,
        "Close Price": 1930.45,
        "Average Price": 1939.3,
        "Total Traded Quantity": 3729409.0,
        "Turnover": 7232442404.05,
        "No. of Trades": 165528.0,
        "Deliverable Qty": 1752041.0,
        "% Dly Qt to Traded Qty": 46.98
    }
]
}

How can I modify it by Python?

2 Answers

If you json file is named data.json, then you can use this script:

import json

with open('data.json', 'r') as f_in:
    data = json.load(f_in)

with open('data_out.json', 'w') as f_out:
    json.dump({'tcs': data}, f_out, indent=4)

The output will be data_out.json with content:

{
    "tcs": [
        {
            "Symbol": "TCS",
            "Series": "EQ",
            "Date": "04-May-2020",
            "Prev Close": 2014.45,
            "Open Price": 1966.0,
            "High Price": 1966.0,
            "Low Price": 1913.65,
            "Last Price": 1930.5,
            "Close Price": 1930.45,
            "Average Price": 1939.3,
            "Total Traded Quantity": 3729409.0,
            "Turnover": 7232442404.05,
            "No. of Trades": 165528.0,
            "Deliverable Qty": 1752041.0,
            "% Dly Qt to Traded Qty": 46.98
        }
    ]
}
def updateJsonContent():
    jsonFile = open("your_json_file.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile)  
    jsonFile.close()  

    updated_data = {"tcs":data}

    # Save the changes to JSON file
    jsonFile = open("your_json_file.json", "w+")
    jsonFile.write(json.dumps(updated_data))
    jsonFile.close()
Related