我運行此代碼并得到以下錯誤
df = pd.read_sql(f"select id, jsonresponse from ResponseDetails;", engine)
all_df = df[['id', 'jsonresponse']].values.tolist()
for x in all_df:
jsn1 = x[1]
print(jsn1)
print(json.loads(jsn1))
Output:
>
{\"request_id\":\"2312\",\"task_id\":\"423432\",\"group_id\":\"43r23\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}
---------------------------------------------------------------------------
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
為了產生上述錯誤,我將上面的 json 字串存盤到變數中。但這一次它完美地作業了。
jsn2 = '{\"request_id\":\"2312\",\"task_id\":\"423432\",\"group_id\":\"43r23\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}'
print(json.loads(jsn2))
Output:
>
{'request_id': '2312',
'task_id': '423432',
'group_id': '43r23',
'success': True,
'response_code': '100',
'response_message': 'Valid Authentication'}
怎么jsn2不一樣jsn1。我怎么能json.load() jsn1變。
編輯:仍然嘗試下面的代碼
for x in all_df:
jsn1 = x[1]
dmp = json.dumps(jsn1)
print(dmp)
print(json.loads(dmp))
輸出:
"{\\\"request_id\\\":\\\"7a4974bb-8b43-4ff0-bc7c-8a0923aef03d\\\",\\\"task_id\\\":\\\"ce57782d-a56e-4be7-a803-18dcd71588a2\\\",\\\"group_id\\\":\\\"268eba73-fe5a-4cd2-a80e-11fc2d06f127\\\",\\\"success\\\":true,\\\"response_code\\\":\\\"100\\\",\\\"response_message\\\":\\\"Valid Authentication\\\"}"
{\"request_id\":\"7a4974bb-8b43-4ff0-bc7c-8a0923aef03d\",\"task_id\":\"ce57782d-a56e-4be7-a803-18dcd71588a2\",\"group_id\":\"268eba73-fe5a-4cd2-a80e-11fc2d06f127\",\"success\":true,\"response_code\":\"100\",\"response_message\":\"Valid Authentication\"}
uj5u.com熱心網友回復:
將Python物件轉換為Json字串使用json.dumps()
以及將Json字串轉換為Python物件使用json.loads()
所以你的代碼看起來像這樣
for x in all_df:
jsn1 = json.dumps(x[1])
print(jsn1)
print(json.loads(jsn1))
更新
您的字串未正確轉義,因此請嘗試這樣
for x in all_df:
jsn1 = json.dumps(x[1])
jsn1 = bytes(jsn1, "utf-8").decode("unicode_escape")
print(jsn1)
print(json.loads(jsn1))
uj5u.com熱心網友回復:
正如@craigb 建議的那樣。以下更改對我有用
for x in all_df:
jsn1 = x[1].replace('\\"','"')
print(json.loads(jsn1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/526265.html
