Home > Software design >  Is there a way to set key values within a JSON object as the key for that object in python?
Is there a way to set key values within a JSON object as the key for that object in python?

Time:10-05

I have a lot of JSON data that basically only comprises JSON objects in an array(extract below).

[
{
    "unix": "1633224900000",
    "date": "2021-10-03 01:35:00",
    "open": "47314.54000000",
    "high": "47314.54000000",
    "low": "47298.89000000",
    "close": "47310.25000000"
},
{
    "unix": "1633224840000",
    "date": "2021-10-03 01:34:00",
    "open": "47312.78000000",
    "high": "47340.42000000",
    "low": "47300.99000000",
    "close": "47314.53000000"
}

As you can see all the objects don't have keys to describe them. My question is if there is a way I could programmatically assign each object in the JSON file with a key identical to the "unix" value within the object?

There is an example of how I would like it to be below:

[
"1633224900000": {
    "unix": "1633224900000",
    "date": "2021-10-03 01:35:00",
    "symbol": "BTC/USDT",
    "open": "47314.54000000",
    "high": "47314.54000000",
    "low": "47298.89000000",
    "close": "47310.25000000"
},
"1633224840000": {
    "unix": "1633224840000",
    "date": "2021-10-03 01:34:00",
    "symbol": "BTC/USDT",
    "open": "47312.78000000",
    "high": "47340.42000000",
    "low": "47300.99000000",
    "close": "47314.53000000"
}

Thanks in advance.

CodePudding user response:

You could use a Dict Comprehension:

records = [
    {
        "unix": "1633224900000",
        "date": "2021-10-03 01:35:00",
        "open": "47314.54000000",
        "high": "47314.54000000",
        "low": "47298.89000000",
        "close": "47310.25000000"
    },
    {
        "unix": "1633224840000",
        "date": "2021-10-03 01:34:00",
        "open": "47312.78000000",
        "high": "47340.42000000",
        "low": "47300.99000000",
        "close": "47314.53000000"
    }
]

output = {record["unix"]: record for record in records}

print(output)

Output:

{'1633224840000': {'close': '47314.53000000',
                   'date': '2021-10-03 01:34:00',
                   'high': '47340.42000000',
                   'low': '47300.99000000',
                   'open': '47312.78000000',
                   'unix': '1633224840000'},
 '1633224900000': {'close': '47310.25000000',
                   'date': '2021-10-03 01:35:00',
                   'high': '47314.54000000',
                   'low': '47298.89000000',
                   'open': '47314.54000000',
                   'unix': '1633224900000'}}
  • Related