ValueError: Invalid control character at: line 1 column 122(char 123)
出現錯誤的原因是字符串中包含了回車符(\r)或者換行符(\n)
解決方案:
- 轉義
json_data = json_data.replace('\r', '\\r').replace('\n', '\\n')
- 使用關鍵字strict
json.loads(json_data, strict=False)
ValueError: Expecting , delimiter: line 13 column 650 (char 4186)
原因:json數據不合法,類似“group_buy_create_description_text”: “1. Select the blue “Buy” button to let other shoppers buy with you.這樣的內容出現在json數據中。
解決方案:
將類似的情形通過正則篩選出來通過下面的方式處理。
正則表達式如下:
json_data = json_data.replace('""', '"########"')
js_str = '"[\s\S]+?":\s?"([\s\S]+?)"\}?\}?\]?,'
後續使用中發現無法匹配value爲空的情況,故先做一下預處理
這個正則可以匹配到大部分的key,value中的value值,但是也有例外,暫時的處理方法是如果匹配結果中包含”{“, “}”, “[“, “]”這樣的字符,說明是匹配失敗結果,跳過處理。其他的使用下邊的方法替換掉可能出問題的字符。
如果大家有更好的正則匹配方式,歡迎隨時批評指正。
def htmlEscape(input) {
if not input
return input;
input = input.replace("&", "&");
input = input.replace("<", "<");
input = input.replace(">", ">");
input = input.replace(" ", " ");
input = input.replace("'", "'"); //IE暫不支持單引號的實體名稱,而支持單引號的實體編號,故單引號轉義成實體編號,其它字符轉義成實體名稱
input = input.replace("\"", """); //雙引號也需要轉義,所以加一個斜線對其進行轉義
input = input.replace("\n", "<br/>"); //不能把\n的過濾放在前面,因爲還要對<和>過濾,這樣就會導致<br/>失效了
return input;
}