Starting with a DataFrame that has a form such as this
df = pl.DataFrame([{"SkuId":1}])
shape: (1, 1)
┌───────┐
│ SkuId │
│ --- │
│ i64 │
╞═══════╡
│ 1 │
└───────┘
How can I write it to a JSON file with this format?
"SkuId": {"source": 1},
2
Answers
You can first transform the Polars DataFrame to a dictionary and then manipulate the dictionary to match the format you want before writing it to a JSON file.
Polars has two (really 3) nested types. There are Structs which are like objects (aka
{}
) in JSON and Lists which are like Arrays (aka[]
).To get it to put JSON in the format you’re looking for, you need to make a struct.
Of course, if you put a file path inside
write_json()
then it’ll write it to the file instead of just printing it to stdout.