在Python中从字符串加载JSON时出错

时间:2017-12-31 11:41:06

标签: python json python-3.x

使用json.loads()

加载以下内容时遇到问题
json.loads("""{"columnName": "ML_Status_Flags_1.LAST_RESOLVED_DATE",
      "columnId": "3",
      "columnIndex": 5, 
      "formulaString": "\u003dGROUPBY(ASdate(Formatdate(#Remedy_CL_!LAST_RESOLVED_DATE_ML_Status_Flags_1;\"dd-MM-yyyy\");\"dd-MM-yyyy\"))"
    }""")

我收到以下错误

ERROR:root:An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 9))

并且在错误结束时我得到了这个

JSONDecodeError: Expecting ',' delimiter: line 4 column 106 (char 215)

3 个答案:

答案 0 :(得分:2)

在日期换掉单打的双引号,我不相信它们是用字符串中的\来转义的

json.loads("""{"columnName": "ML_Status_Flags_1.LAST_RESOLVED_DATE",
      "columnId": "3",
      "columnIndex": 5, 
      "formulaString": "\u003dGROUPBY(ASdate(Formatdate(#Remedy_CL_!LAST_RESOLVED_DATE_ML_Status_Flags_1;'dd-MM-yyyy');'dd-MM-yyyy'))"
    }""")

答案 1 :(得分:1)

您需要使用双反斜杠\\来转义双引号:

json.loads("""{"columnName": "ML_Status_Flags_1.LAST_RESOLVED_DATE",
       "columnId": "3",
       "columnIndex": 5,
       "formulaString": "\u003dGROUPBY(ASdate(Formatdate(#Remedy_CL_!LAST_RESOLVED_DATE_ML_Status_Flags_1;\\"dd- MM-yyyy\\");\\"dd-MM-yyyy\\"))"
     }""")

答案 2 :(得分:1)

看起来像一个有效的json。添加' r'之前的伎俩。有关' r'的更多信息,请参阅此处和' u':https://stackoverflow.com/a/2081708/7386332

原因是\是Python中的转义字符,r'确保不考虑这一点。

import json

json.loads(r"""{"columnName": "ML_Status_Flags_1.LAST_RESOLVED_DATE",
      "columnId": "3",
      "columnIndex": 5, 
      "formulaString": "\u003dGROUPBY(ASdate(Formatdate(#Remedy_CL_!LAST_RESOLVED_DATE_ML_Status_Flags_1;\"dd-MM-yyyy\");\"dd-MM-yyyy\"))"
    }""")

返回

{'columnId': '3',
 'columnIndex': 5,
 'columnName': 'ML_Status_Flags_1.LAST_RESOLVED_DATE',
 'formulaString': '=GROUPBY(ASdate(Formatdate(#Remedy_CL_!LAST_RESOLVED_DATE_ML_Status_Flags_1;"dd-MM-yyyy");"dd-MM-yyyy"))'}