I am having some trouble getting the following dataframe to a JSON structure. I've tried a few things but can't quite get to the last bit. So I have a data frame with the following
serialNumber | date | part | value | name
--------------|------------|-------|-------|----------------
ABC0001 | 01/10/2019 | Part1 | ABC1 | ABC
ABC0001 | 01/10/2019 | Part1 | ABC2 | XYZ
ABC0001 | 02/10/2019 | Part2 | ABC3 | ASF
ABC0001 | 02/10/2019 | Part2 | ABC4 | TSR
And need it in the format of
{ "SerialNumber": "ABC001",
"detail": [ { "part": "Part1",
"date":"01/10/2019",
"extras": [ { "value": "ABC1",
"name": "ABC"
},
{ "value": "ABC2",
"name": "XYZ"
}]
},
{ "part": "Part2",
"date":"02/10/2019",
"extras": [ { "value": "ABC3",
"name": "ASF"
},
{ "value": "ABC4",
"name": "TSR"
}]
]
}
So grouping serialnumber, then data and part, then value and name. I've had a look at some answers here and here, the last one helped a lot
df.groupby(['serialNumber', 'Part']).apply(
lambda r: r[['Value', 'identifierName']].to_dict(orient='records')
).unstack('serialNumber').apply(lambda s: [
{s.index.name: idx, 'detail=': value}
for idx, value in s.items()]
).to_json(orient='records')
which gives me
[
{
"ABC0001":{
"Part":"Part1",
"detail=":[
{
"Value":"ABC1",
"identifierName":"ABC"
},
{
"Value":"ABC2",
"identifierName":"XYZ"
}
]
}
},
{
"ABC0001":{
"Part":"Part2",
"detail=":[
{
"Value":"ABC3",
"identifierName":"ASF"
},
{
"Value":"ABC4",
"identifierName":"TSR"
}
]
}
}
]
but breaks down when I add Date, and doesn't show the label of serial number Suggestions?? tips?