Starting with a DataFrame that has a form such as this
<code>df = pl.DataFrame([{"SkuId":1}])
shape: (1, 1)
┌───────┐
│ SkuId │
│ --- │
│ i64 │
╞═══════╡
│ 1 │
└───────┘
</code>
<code>df = pl.DataFrame([{"SkuId":1}])
shape: (1, 1)
┌───────┐
│ SkuId │
│ --- │
│ i64 │
╞═══════╡
│ 1 │
└───────┘
</code>
df = pl.DataFrame([{"SkuId":1}])
shape: (1, 1)
┌───────┐
│ SkuId │
│ --- │
│ i64 │
╞═══════╡
│ 1 │
└───────┘
How can I write it to a JSON file with this format?
<code>"SkuId": {"source": 1},
</code>
<code>"SkuId": {"source": 1},
</code>
"SkuId": {"source": 1},
1
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.
<code>df.select(SkuId=pl.struct(source=pl.col('SkuId'))).write_json()
[{"SkuId":{"source":1}}]
</code>
<code>df.select(SkuId=pl.struct(source=pl.col('SkuId'))).write_json()
[{"SkuId":{"source":1}}]
</code>
df.select(SkuId=pl.struct(source=pl.col('SkuId'))).write_json()
[{"SkuId":{"source":1}}]
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.