我如何在python中创建空的json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16436133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:36:50  来源:igfitidea点击:

How can i create the empty json object in python

pythonjson

提问by user2330497

I have this code

我有这个代码

json.loads(request.POST.get('mydata',dict()))

But i get this error

但我收到这个错误

No JSON object could be decoded

I just want that if don't have mydatain POST then i don't get that error

我只是希望如果mydata在 POST 中没有,那么我就不会收到那个错误

采纳答案by defuz

Simply:

简单地:

json.loads(request.POST.get('mydata', '{}'))

Or:

或者:

data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {}

Or:

或者:

if 'mydata' in request.POST:
    data = json.loads(request.POST['mydata'])
else:
    data = {} # or data = None

回答by Bibhas Debnath

loads()takes a json formatted string and turns it into a Python object like dict or list. In your code, you're passing dict()as default value if mydatadoesn't exist in request.POST, while it should be a string, like "{}". So you can write -

loads()接受一个 json 格式的字符串并将其转换为 Python 对象,如 dict 或 list。在您的代码中,dict()如果mydata中不存在request.POST,则作为默认值传递,而它应该是一个字符串,例如"{}". 所以你可以写 -

json_data = json.loads(request.POST.get('mydata', "{}"))

Also remember, the value of request.POST['mydata']must be JSON formatted, or else you'll get the same error.

还要记住, 的值request.POST['mydata']必须是 JSON 格式,否则你会得到同样的错误。