python eval vs ast.literal_eval vs JSON decode

后端 未结 4 1636
慢半拍i
慢半拍i 2020-11-28 13:03

I am converting 2 MB of data as a string into a dict. The input is serialized in JSON.

Anyways I am currently using ast.literal_eval and I get the dictionary I want,

4条回答
  •  悲哀的现实
    2020-11-28 13:27

    Yes, there's definitely a reason: eval() is evil. Your code might read untrusted data one day, an this would allow an attacker to run arbitrary code on your machine.

    You shouldn't use ast.literal_eval() to decode JSON either. It cannot decode every valid JSON string and is not meant to be used for this purpose. Simply use json.loads(), it's reasonably fast.

提交回复
热议问题