![](/img/trans.png)
[英]how to convert string json inside a valid json into valid json python
[英]How to return this valid json data in Python?
我測試了使用Python轉換卷曲以獲得一些數據的能力。
import requests
import json
username="abc"
password="123"
headers = {
'Content-Type': 'application/json',
}
params = (
('version', '2017-05-01'),
)
data = '{"text":["This is message one."], "id":"en-es"}'
response = requests.post('https://somegateway.service/api/abc', headers=headers, params=params, data=data, auth=(username, password))
print(response.text)
以上工作正常。 它返回json數據。 似乎[“這是消息一。”]是一個列表。 我想使用加載文件的變量來替換此列表。 我試過了:
with open(f,"r",encoding='utf-8') as fp:
file_in_list=fp.read().splitlines()
toStr=str(file_in_list)
data = '{"text":'+toStr+', "id":"en-es"}'
response = requests.post('https://somegateway.service/api/abc', headers=headers, params=params, data=data, auth=(username, password))
print(response.text)
但它在下面返回了錯誤。
{
"code" : 400,
"error" : "Mapping error, invalid JSON"
}
你能幫我嗎? 如何獲得有效的response.text?
謝謝。
更新:
f的內容僅包含以下五行:
This is message one.
this is 2.
this is three.
this is four.
this is five.
現有代碼失敗的原因是,將str
應用於字符串列表只會很少給您有效的JSON。 他們不打算做同樣的事情。 JSON僅允許使用雙引號引起來的字符串; Python允許單引號和雙引號字符串。 而且,除非您的所有字符串碰巧都包含'
字符,否則Python會將其用單引號引起來:
>>> print(["abc'def"]) # gives you valid JSON, but only by accident
["abc'def"]
>>> print(["abc"]) # does not give you valid JSON
['abc']
如果要獲取字符串列表的有效JSON編碼,請不要嘗試通過誘使str
偶然為您提供有效的JSON,只需使用json
模塊即可:
toStr = json.dumps(file_in_list)
但是,更簡單地說,您不應該首先弄清楚如何構造JSON字符串。 只需創建一個字典並json.dumps
整個事情:
data = {"text": file_in_list, "id": "en-es"}
data_str = json.dumps(data)
能夠做到這一點幾乎就是JSON的全部要點:這是一種自動序列化所有主要腳本語言所共有的所有類型的簡單方法。
或者,甚至更好的是,讓requests
通過傳遞json
參數而不是data
參數來為您完成此操作:
data = {"text": file_in_list, "id": "en-es"}
response = requests.post('https://somegateway.service/api/abc', headers=headers, params=params, json=data, auth=(username, password))
這也會自動為您設置Content-Type
標頭為application/json
。 您沒有這樣做-盡管許多服務器會接受沒有輸入的輸入,但這是非法的,並且有些服務器不允許這樣做。
有關更多詳細信息,請參閱requests
文檔中的“ 更復雜的POST請求 ”部分。 但是實際上沒有更多細節。
toStr = json.dumps(file_in_list)
假設您的文件包含類似String_A String_B
您需要確保toStr為:
[
和]
括起來 因此,您的原始json(作為字符串)等於'{"text":["String_A", "String_B"], "id":"en-es"}'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.