2017-07-31 455 views
0

我有JSON字符串列表,看起來像這樣:將JSON值中的雙引號轉換爲單引號?

[ 
    { 
    "info": "https://google.com/athens", 
    "locationdetails": "Greece" 
    ... 
    }, 
    { 
    "info": "italytourism.com", 
    "locationdetails": "Gardens of "Little Italy" indoors" 
    ... 
    } 
    ... 
] 

一些在這個JSON值有雙引號中他們的(如「小意大利」,並且創建了一個錯誤,因爲在Python只有單引號可以在雙引號內使用(或者是一個轉義字符)我想知道通過這個json字符串和鍵列表的最好方法是什麼,並將雙引號內的值字符串轉換爲單引號。建議使用json.dumps(jsonlist)來解決這個問題,但這並不適用於我..感謝您的幫助!

+7

這是無效的json。您需要將這些引號從頭開始。 –

+0

你確定嗎?我已經能夠像普通的json那樣訪問鍵和值。但是如果是這種情況,我們需要將其中的「」替換爲單引號,以便它可以是有效的json並用於其他函數中。有沒有簡單的方法來做到這一點? – nm44

+1

嗯......有趣。你能分享一下似乎有用的代碼嗎?另外,我不確定是否有...正則表達式可能工作。你如何得到這個json? –

回答

1

正如評論中所述,您的示例是無效的JSON。使用json庫,請注意引號正確轉義,並且數據可以從JSON格式序列化到JSON格式。

import json 

data = [ 
    { 
    'info': 'https://google.com/athens', 
    'locationdetails': 'Greece' 
    }, 
    { 
    'info': 'italytourism.com', 
    'locationdetails': 'Gardens of "Little Italy" indoors' 
    } 
] 

j = json.dumps(data,indent=2) 
print(j) 

data2 = json.loads(j) 
print(data2 == data) 
[ 
    { 
    "info": "https://google.com/athens", 
    "locationdetails": "Greece" 
    }, 
    { 
    "info": "italytourism.com", 
    "locationdetails": "Gardens of \"Little Italy\" indoors" 
    } 
] 
True 
1

這個表達式維修在有限的例子你的壞JSON給出的,但我不希望它爲所有可以想象的例子是穩健的。例如,它假定除了有問題的雙引號字符外,你的值中只有字母數字字符和空格。

import re 
import json 

jsonString = """ 
[ 
    { 
    "info": "https://google.com/athens", 
    "locationdetails": "Greece" 

    }, 
    { 
    "info": "italytourism.com", 
    "locationdetails": "Gardens of "Little Italy" indoors" 
    } 
] 
""" 
data = json.loads(re.sub(r'": "([\s\w]*)"([\s\w]+)"([\s\w]*)"(,?)', r'": "\1' + "'" + r'\2' + "'" + r'\3"\4', jsonString))