添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more

I have JSON data which looks like this. If not for null (without quotes as a string), I could have used ast module's literal_eval to convert the above to a dictionary.

A dictionary in Python cannot have null as value but can have "null" as a value. How do I convert the above to a dictionary that Python recognizes?

You should use the built-in json module , which was designed explicitly for this task:

>>> import json
>>> data = '''
... {
...   "abc": null,
...   "def": 9
... }
... '''
>>> json.loads(data)
{'def': 9, 'abc': None}
>>> type(json.loads(data))
<class 'dict'>

By the way, you should use this method even if your JSON data contains no null values. While it may work (sometimes), ast.literal_eval was designed to evaluate Python code that is represented as a string. It is simply the wrong tool to work with JSON data.

hd1 - for some reason. iCodez comment showed up first. Sorry! so i had to mark it as the answer but thanks Good show! – user2921139 Nov 26 '14 at 2:11 @user2921139: If you really want to translate null to "null" rather than None as your question implies, you will need to do a bit of extra work. But I suspect that you don't want that. – abarnert Nov 26 '14 at 2:34

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.