Does converting json to dict with eval a good choice?

≯℡__Kan透↙ 提交于 2019-12-12 08:31:28

问题


I am getting a json object from a remote server, and converting it to a python string like this:

a = eval(response)

Is this stupid in any way, or do I have a better option?


回答1:


Using eval is not a good way to process JSON:

  1. JSON isn't even valid Python, because of true, false, and null.

  2. eval will execute arbitrary Python code, so you are at the mercy of malicious injection of code.

Use the json module available in the standard library instead:

import json
data = json.loads("[1, 2, 3]")

If you're using a version of Python older than 2.6, you'll need to download the module yourself. It's called simplejson and can be downloaded from PyPi.




回答2:


Yes, very. Use a json decoder instead:

>>> from simplejson import loads
>>> loads(response)


来源:https://stackoverflow.com/questions/7282905/does-converting-json-to-dict-with-eval-a-good-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!