0

I have the following json (loaded from a pandas dataframe):

[{
    "id": "fc29706f-e041-46f6-88ff-cbab891da63c",
    "account": "21",
    "date": "2021-12-06",
    "amount": "54.4"
}, {
    "id": "508784e4-370d-450d-bed0-8f52da7469dd",
    "account": "21",
    "date": "2022-01-10",
    "amount": "20"

}]

and need to convert it into:

{
    "transactions": [{
        "id": "fc29706f-e041-46f6-88ff-cbab891da63c",
        "account": "21",
        "date": "2021-12-06",
        "amount": "54.4"
    }, {
        "id": "508784e4-370d-450d-bed0-8f52da7469dd",
        "account": "21",
        "date": "2022-01-10",
        "amount": "20"
    }]
}

in order to sent it to an API in this format.

What's the best way to do this conversion in python please?

===== stack overflow made me add this ====

The original dataframe data is:

  id        date amount category account  \
0  fc29706f-e041-46f6-88ff-cbab891da63c  2021-12-06   54.4    21
1  508784e4-370d-450d-bed0-8f52da7469dd  2022-01-10     20    20
 

and I converted it to json using

result = df.to_json(orient='records')

and this puts the data into the correct orientation above, but how can I insert the 'result' as an array into the value of a key called 'transactions'?

TIA

john
  • 145
  • 1
  • 4

1 Answers1

0

Use df.to_dict() to covert the dataframe to a dictionary then create a new dictionary with "transactions" as the key and the converted dictionary as the value and finally use json.dumps() to convert the new dictionary to json.

import json

result = df.to_dict(orient="records")

data = {"transactions": result}
json_out = json.dumps(data)
print(json_out)

{"transactions": [{"id": "fc29706f-e041-46f6-88ff-cbab891da63c", "account": "21", "date": "2021-12-06", "amount": "54.4"}, {"id": "508784e4-370d-450d-bed0-8f52da7469dd", "account": "21", "date": "2022-01-10", "amount": "20"}]}

print output in an indented format

json_out = json.dumps(result, indent=2, default=int)
print(json_out)

{
  "transactions": [
    {
      "id": "fc29706f-e041-46f6-88ff-cbab891da63c",
      "account": "21",
      "date": "2021-12-06",
      "amount": "54.4"
    },
    {
      "id": "508784e4-370d-450d-bed0-8f52da7469dd",
      "account": "21",
      "date": "2022-01-10",
      "amount": "20"
    }
  ]
}
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34