解析有效的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對象或數組。有什麼建議麼?
我認爲它簡單易讀,而不是使用複雜的RegEx。 – thefourtheye
您正在導入Json。只需使用.parse() – Law