python用双引号解析json数据 [英] python parsing json data with double quotes
本文介绍了python用双引号解析json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在双引号内解析json数据:
How do you parse json data with double quotes within:
json.loads('
{
"time":"1410661614",
"text":"This is great",
"from":
{
"username":"mrb",
"id":"5071",
"full_name":"Free "Mrb"" #here is the problem
},
"id":"8090107"
}
')
python返回值:
python returns:
ValueError: Expecting ',' delimiter: line 1 column 107 (char 106)
推荐答案
谁编写了在字符串中发出那些未转义引号的程序,都需要一个 serious 与...交谈
Whoever wrote the program that emits those unescaped quotes inside strings needs a serious talking to...
正如Martijn所说,解析任意疯狂的报价并不容易。
As Martijn said, parsing arbitrary crazy quotes is not easy.
OTOH,如果JSON的格式正确,并且令人讨厌的字符串没有越过边界,那么 so 也不错。例如,
OTOH, if the JSON is otherwise well-formed, and the offending strings don't cross line boundaries, then it's not so bad. Eg,
#! /usr/bin/env python
''' Escape quotes in malformed JSON value strings
Written by PM 2Ring 2014.09.19
'''
import re
data = [
''' "evil_name":"Free "Mrb"",''',
''' "good_name":"Alan Turing",'''
]
for line in data:
pre, val = line.split(':')
parts = re.split('(")', val)
n = parts.count('"')
if n > 2:
i = 1
a = []
for c in parts:
if c == '"':
if 1 < i < n:
c = '\\"'
i += 1
a.append(c)
line = pre + ':' + ''.join(a)
print line
输出
"evil_name":"Free \"Mrb\"",
"good_name":"Alan Turing",
这篇关于python用双引号解析json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文