2014-09-19 59 views
0

你如何用雙引號解析中JSON數據:蟒蛇解析JSON數據用雙引號

json.loads(' 
{ 
"time":"1410661614", 
"text":"This is great", 
"from": 
    { 
     "username":"mrb", 
     "id":"5071", 
     "full_name":"Free "Mrb"" #here is the problem 
    }, 
"id":"8090107" 
} 
') 

蟒蛇回報:

ValueError: Expecting ',' delimiter: line 1 column 107 (char 106) 
+0

如果你不能修復產生無效的JSON,你可能需要編寫一些代碼解析之前修復它的代碼。 – wRAR 2014-09-19 09:52:09

+1

您的JSON格式不正確,難以解決*。改爲在源處解決問題。 – 2014-09-19 09:53:10

回答

1

您可以輕鬆地逃避雙引號解決這個問題( \"

import json 

json.loads(""" 

{ 
"time":"1410661614", 
"text":"This is great", 
"from": 
    { 
     "username":"mrb", 
     "id":"5071", 
     "full_name":"Free \\"Mrb\\"" 
    }, 
"id":"8090107" 
} 

""") 

正如評論所說,更好地解決JSON發電機正常轉義雙引號,這將是很難解析和糾正JSON文件。

1

誰寫發出字符串內的轉義引號的程序需要一個嚴重說話......

正如馬亭說,解析任意瘋狂的報價是不容易的。

OTOH,如果JSON格式正確,並且違規字符串不跨越線條邊界,那麼它不是,所以不好。例如,

#! /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",