2016-01-23 65 views
2

解析有效的JSON對象或數組我有一個字符串,它可以是兩種形式之一:從字符串

name multi word description {...} 

name multi word description [...] 

其中{...}[...]是任何有效的JSON。我有興趣解析出字符串的JSON部分,但我不確定最好的方法(特別是因爲我不知道這兩個字符串是哪一個)。這是我目前的方法:

import json 

string = 'bob1: The ceo of the company {"salary": 100000}' 
o_ind = string.find('{') 
a_ind = string.find('[') 

if o_ind == -1 and a_ind == -1: 
    print("Could not find JSON") 
    exit(0) 

index = min(o_ind, a_ind) 
if index == -1: 
    index = max(o_ind, a_ind) 

json = json.loads(string[index:]) 
print(json) 

它的工作原理,但我不禁感覺它可以做得更好。我想也許正則表達式,但我遇到了麻煩匹配子對象和數組,而不是最外面的json對象或數組。有什麼建議麼?

+3

我認爲它簡單易讀,而不是使用複雜的RegEx。 – thefourtheye

+0

您正在導入Json。只需使用.parse() – Law

回答

4

您可以通過檢查的{[存在找到JSON的開始,然後一切保存到字符串的結尾爲捕獲組:

>>> import re 
>>> string1 = 'bob1: The ceo of the company {"salary": 100000}' 
>>> string2 = 'bob1: The ceo of the company ["10001", "10002"]' 
>>> 
>>> re.search(r"\s([{\[].*?[}\]])$", string1).group(1) 
'{"salary": 100000}' 
>>> re.search(r"\s([{\[].*?[}\]])$", string2).group(1) 
'["10001", "10002"]' 

這裏\s([{\[].*?[}\]])$分解爲:

  • \s - 單個空格字符
  • 括號是capturing group
  • [{\[]將匹配單個{[(後者需要用反斜槓轉義)
  • .*?non-greedy匹配爲任何字符的任何次數
  • [}\]]將匹配單個}](後者需要用反斜槓轉義)
  • $意味着字符串的末尾

或者,您可以使用re.split()將字符串拆分爲一個空格,後面跟着一個{[(帶有積極的展望)並獲取最後一個項目。它適用於樣本輸入您提供的,但不知道這是一般可靠:

>>> re.split(r"\s(?=[{\[])", string1)[-1] 
'{"salary": 100000}' 
>>> re.split(r"\s(?=[{\[])", string2)[-1] 
'["10001", "10002"]' 
2

你可以使用簡單的|在正則表達式匹配這兩者缺一子:

import re 
import json 

def json_from_s(s): 
    match = re.findall(r"{.+[:,].+}|\[.+[,:].+\]", s) 
    return json.loads(match[0]) if match else None 

而且有些測試:

print json_from_s('bob1: The ceo of the company {"salary": 100000}') 
print json_from_s('bob1: The ceo of the company ["salary", 100000]') 
print json_from_s('bob1') 
print json_from_s('{1:}') 
print json_from_s('[,1]') 

輸出:

{u'salary': 100000} 
[u'salary', 100000] 
None 
None 
None 
+0

考慮這種情況:''bob1:公司的首席執行官[{「salary」:100000}]''。正則表達式只匹配內部json對象而不匹配外部json數組 – RPGillespie

+0

我只關注ops問題和解釋 – tinySandy

+0

我是OP,我給出的解釋是字符串可以是'name multi word description [。 ..]'。我上面給你的情況遵循這種模式,但正則表達式沒有捕獲它。 – RPGillespie