Django解码Json错误

时间:2014-11-20 04:16:21

标签: json django

我有这个json数据,我发布到Django

[[LAT2:1.3178775, LON1:103.7608174, LON2:103.7733836, LAT1:1.3104325, YPIXELS:378, XPIXELS:400, MINZ:40, XKNOTS:26, YKNOTS:24, MAXZ:80], [node:51, z:63.462589, y:1.312762, x:103.766148]]

获取错误:期望值:第1行第3列(字符2)

我的代码:

jsonStr = request.body.decode(encoding='UTF-8')
jsonObj = json.loads(jsonStr)

1 个答案:

答案 0 :(得分:1)

你的字符串不是有效的json。 key:值对必须包含在大括号中,并且必须引用键。例如:{"key" : "value"}

至少您必须将字符串转换为以下格式:

[{"LAT2":1.3178775, "LON1":103.7608174, "LON2":103.7733836, "LAT1":1.3104325, "YPIXELS":378, "XPIXELS":400, "MINZ":40, "XKNOTS":26, "YKNOTS":24, "MAXZ":80}, {"node":51, "z":63.462589, "y":1.312762, "x":103.766148}]'

如果你知道字符串中的键是一致的,那么这是一种没有正则表达式的方法:

 # Bracket the {key : value} structures:
 input = '[' + input[1:-1].replace('[', '{').replace(']', '}') + ']'

 # Wrap the keys in double quotes:
 keys = ('LAT2', 'LON1', 'LON2', 'LAT1', 'YPIXELS', 'XPIXELS', 
         'XKNOTS', 'YKNOTS', 'MINZ', 'MAXZ', 'node', 'z', 'y', 'x')

 for key in keys:
      input = input.replace(key, '"' + key + '"')