Hi I'm new in DRF and need a help . I write API.Then user ,for example, put in url http://api.example/people , then he get value from "attributes" -"name": "John","age": 80,"gender": "male". I get this data from db and give information for user, that`s why I must serialize this data.
{
"name": "John",
"age": 80,
"gender": "male"
}
field "type" is dynamic for example can be "animal" http://api.example/animal .Field "included" is JSONField() in model .My problem is in point, when I must get field fields from "included" in views.py for serialization , because it is json and I don't know how I must work with it . Maybe json.dump() but then I got str and can't convert in dict . Maybe someone give me some advice, please.
{
"data": [{
"id": "1",
"attributes": {
"title": "JSON:API paints my bikeshed!",
"body": "The shortest article. Ever.",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z"
},
"relationships": {
"author": {
"data": {"id": "42", "type": "people"}
}
}
}],
"included": [
{
"type": "people",
"id": "42",
"attributes": {
"name": "John",
"age": 80,
"gender": "male"
}
}
]
}
I
CodePudding user response:
Getting specific data out of json
can be done as follows. If your json_data looks like this e.g.:
json_data = [{"id": "1"}]
Than you could get the id
like this:
id : int = json_data['id']
So basically you just need your json
data and can access all values by its "name" using brackets ([]
)
CodePudding user response:
you probably want json.loads and to load it into ordereddict, not normal dict, you need to provide additional argument
example:
import json
from collections import OrderedDict
data = json.loads(some_json_data, object_pairs_hook=OrderedDcit)