谁能告诉我我做错了什么? ast.literal_eval格式错误的节点或字符串python3

时间:2015-03-11 15:40:10

标签: python

平,

我正在尝试使用ast.literal_eval将dict从字符串转换为dict,但我出于某种原因会出错。我真的无法弄清楚我做错了什么,谁能告诉我为什么它不会工作?

>>> ast.literal_eval("""{
   "jsonrpc": "2.0",
   "id": 1,
   "result": {
      "moreAvailable": false,
      "currentOrders": [
         {
            "sizeCancelled": 0.0,
            "marketId": "1.117685350",
            "priceSize": {
               "price": 1.03,
               "size": 30.0
            },
            "placedDate": "2015-03-11T14:55:51.000Z",
            "sizeLapsed": 0.0,
            "orderType": "LIMIT",
            "averagePriceMatched": 1.03,
            "bspLiability": 0.0,
            "matchedDate": "2015-03-11T14:55:57.000Z",
            "sizeRemaining": 0.0,
            "selectionId": 1485567,
            "side": "BACK",
            "betId": "47371597910",
            "persistenceType": "LAPSE",
            "handicap": 0.0,
            "status": "EXECUTION_COMPLETE",
            "regulatorCode": "DANISH GAMBLING AUTHORITY",
            "sizeVoided": 0.0,
            "sizeMatched": 30.0
         }
      ]
   }
}""")
Traceback (most recent call last):
  File "<pyshell#49>", line 33, in <module>
    }""")
  File "C:\Python34\lib\ast.py", line 84, in literal_eval
    return _convert(node_or_string)
  File "C:\Python34\lib\ast.py", line 62, in _convert
    in zip(node.keys, node.values))
  File "C:\Python34\lib\ast.py", line 61, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "C:\Python34\lib\ast.py", line 62, in _convert
    in zip(node.keys, node.values))
  File "C:\Python34\lib\ast.py", line 61, in <genexpr>
    return dict((_convert(k), _convert(v)) for k, v
  File "C:\Python34\lib\ast.py", line 83, in _convert
    raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x00000000052FE278>

1 个答案:

答案 0 :(得分:4)

false不是Python中的有效文字(它是False 1 )。

您似乎正在尝试解析JSON - 在这种情况下json.loads可能正是您正在寻找的内容。


1 实际上,在python2.x上,False根本不是文字,而是名称({ {1}})。 ast.dump(ast.parse('False')) ast.literal_eval True(以及None和{{1}})评估到正确值... {/ sup>