Python 将格式错误的结果保存在JSON中

Python 将格式错误的结果保存在JSON中,python,Python,我正在尝试获取API响应并将其保存到JSON文件中。由于格式不正确的JSON文件,我无法打印输出。我是Python新手。有人能指出正确的方法吗 “内容”是包含以下引号的文本文件 Order growth in France, the U.K. and Spain was more than offset by lower ordersfrom Switzerland, Finland, Norway and Germany.Lastly, you can see orders in the AM

我正在尝试获取API响应并将其保存到JSON文件中。由于格式不正确的JSON文件,我无法打印输出。我是Python新手。有人能指出正确的方法吗

“内容”是包含以下引号的文本文件

Order growth in France, the U.K. and Spain was more than offset by lower ordersfrom Switzerland, Finland, Norway and Germany.Lastly, you can see orders in the AMEA region were up 1%.
Strong growth in Industrial Automation was supplemented by slight growth inElectrification and Motion, while Robotics & Discrete Automation faced a tough market.
Lower orders from China and South Korea were offset bypositive developments in India, Japan, Singapore and UAE.Looking more closely at China, developments were mixed.
……….
代码从这里开始 输出JSON如下所示:我猜JSON保存的缩进有问题

{
"query": "Cash flow from operating activities was $670 million, up 19%.ABB's regional and country order trends for the third quarter are illustrated on Slide 4.",
"topScoringIntent": {
    "intent": "Operating environment",
    "score": 0.171772957
},
"intents": [{
    "intent": "Operating environment",
    "score": 0.171772957
}, {
    "intent": "Competitive advantage",
    "score": 0.121084154
}, {
    "intent": "Operational efficiency",
    "score": 0.06508337
}, {
    "intent": "Value Proposition",
    "score": 0.0280118641
}, {
    "intent": "Critical resources",
    "score": 0.00757621927
}, {
    "intent": "None",
    "score": 0.00240731682
}],
"entities": []
}{
"query": "Specifically, in the United States, our largest market, Electrification order growth was robust apart from large orders, whichhad a tough comparison base.",
"topScoringIntent": {
    "intent": "Competitive advantage",
    "score": 0.252725929
},
"intents": [{
    "intent": "Competitive advantage",
    "score": 0.252725929
}, {
    "intent": "Operating environment",
    "score": 0.06572733
}, {
    "intent": "Operational efficiency",
    "score": 0.0437437519
}, {
    "intent": "Value Proposition",
    "score": 0.0294999164
}, {
    "intent": "Critical resources",
    "score": 0.00545410533
}, {
    "intent": "None",
    "score": 0.00353605044
}],
"entities": []

写作时,可以使用“w+”或“a+”。w+表示写入,它将删除文件先前的内容,另一方面,a+表示追加,并将内容添加到现有文件的末尾

在这种情况下,您应该使用+。

此问题已解决

我只是按照@martineau在评论中所说的去做

import requests

url = "https:...7ebdd7b74&q={}"

payload = {}
headers= {}
if os.path.exists("responsefile.json"):
    os.remove("responsefile.json")
for i in range(0,len(content)):
    response = requests.request("GET", url.format(content[i]), headers=headers, data = payload)
    data=json.loads(response.text.encode('utf8'))
    if os.path.exists("responsefile.json"):
        with open("responsefile.json", 'r') as f:
            old_data = json.load(f)
    else:
        all_data = []
    all_data.append(data)
    with open("responsefile.json", 'w') as f:
        json.dump(all_data, f)

虽然您按照我在评论中给出的建议发布的答案中的代码可能会起作用,但它的效率极低,因为它多次读取和写入文件,如果文件已经存在,则会首先删除它—所有这些都是不必要的

这里有一个更简洁的版本,只(过)写一次文件,但应该完成完全相同的事情。请注意,我无法亲自测试它,因为您从未发布过一个最小的可复制示例-因此它可能有一些小问题

import requests

url = "https:...7ebdd7b74&q={}"

payload = {}
headers= {}

all_data = []
for quote in content:
    response = requests.request("GET", url.format(quote), headers=headers, data=payload)
    data = json.loads(response.text.encode('utf8'))
    all_data.append(data)

with open("responsefile.json", 'w') as f:
    json.dump(all_data, f)

我认为您应该使用模式
“a+”
。是的,这是正确的。感觉很傻。在此之后,JSON的保存方式出现了问题。我得到了一个JSON语法错误。仅仅将一系列JSON对象逐个写入一个文件并不能创建正确的JSON格式的文档。您需要将所有对象放在某种总体容器对象中,例如列表。i、 e.由
[
]
@martineau包围的逗号分隔的一系列对象。谢谢你的评论。这就是我得到的。我已经重新格式化了我的问题。
import requests

url = "https:...7ebdd7b74&q={}"

payload = {}
headers= {}

all_data = []
for quote in content:
    response = requests.request("GET", url.format(quote), headers=headers, data=payload)
    data = json.loads(response.text.encode('utf8'))
    all_data.append(data)

with open("responsefile.json", 'w') as f:
    json.dump(all_data, f)