简体   繁体   中英

django python: how to make json from django queryset

I have query set which returns a json string after converted list.

[{"pid": 1, "loc": "KL", "sid": 1, "sd": "south-1"},
 {"pid": 1, "loc": "KL", "sid": 2, "sd": "north-5"},    
 {"pid": 1, "loc": "KL", "sid": 3, "sd": "west-3"}
]

I have tried many serializer options but no idea how to make the above as:

[{"pid": 1,
  "s": [{"sid": 1, "sd": "south-1",
         "sid": 2, "sd": "north-5",
         "sid": 3, "sd": "west-3"
       }]
}]

Firstly, there's an error in your expected output. You probably meant:

[{"pid": 1,
  "s": [{"sid": 1, "sd": "south-1"},
        {"sid": 2, "sd": "north-5"},
        {"sid": 3, "sd": "west-3"}
       ],
  "loc": "KL"
}]

ie s should be a list of dictionaries and not one dict (and clashing keys). I've added "loc": "KL" since that looks like it's missing.

Assuming each query returns only the same pid and loc , you can create s as a list with each sid and sd in the original query:

>>> q = ... # as above
>>> r = {"pid": q[0]["pid"], "loc": q[0]["loc"]}  # since pid and loc are always the same
>>> r["s"] = [{"sid": x["sid"], "sd": x["sd"]} for x in q]
>>> print r
[{'pid': 1,
  's': [{'sid': 1, 'sd': 'south-1'},
        {'sid': 2, 'sd': 'north-5'},
        {'sid': 3, 'sd': 'west-3'}
       ],
  'loc': 'KL'
}]
>>> print json.dumps(r)  # gives the output as a json string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM