from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
1、JSONRenderer().render(serializer.data)将ReturnDict字典类型转换为字节流
snippet = Snippet(owner=user,code='foo = "bar"\n')
snippet.save()
serializer_context = {
'request': request,
}
serializer = SnippetSerializer(snippet, context=serializer_context)
print(type(serializer.data))
print(serializer.data)
"""
#<class 'rest_framework.utils.serializer_helpers.ReturnDict'>
#{'id': 34, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
"""
content = JSONRenderer().render(serializer.data)
print(type(content))
print(content)
"""
<class 'bytes'>
b'{"id":31,"title":"","code":"foo = \\"bar\\"\\n","linenos":false,"language":"python","style":"friendly"}'
"""
2、JSONParser().parse(stream) #把字节流转换为字典类型
import io
stream = io.BytesIO(content)
data = JSONParser().parse(stream) #把字节流转换为python字典类型
print(type(data))
print(data)
"""
<class 'dict'>
{'id': 31, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}
"""
3、json.dumps()将python对象类型转换为json(str)
4、json.loads()将json(str)转换为python 对象类型