回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图编写一个“with open.json”代码,其中写入了多个产品信息。但是,在.json文件中,每个字典不是用逗号分隔的。这是正常的还是我的代码错了</p>
<pre><code>for product in data['prods']:
product_name = product['name']
prod_id = product['Id']
prod_price = product['price']
link = 'https://24h.pchome.com.tw/prod/' + prod_id
today = str(datetime.date.today())
fileName = today + '_' + keyword + '_Pchome.json'
try:
with open(fileName, 'a', encoding='utf-8') as f:
json.dump({
"名稱":product_name,
"價格":prod_price,
"網址":link,
}, f, ensure_ascii=False, indent=4, skipkeys=True)
except Exception as err:
print(str(err))
</code></pre>
<p>已编辑:将我的代码更改为类似这样的内容(因为人们想知道更多信息。)</p>
<pre><code>keyword = str(input('找什麼? '))
pages = 10
parse_word = urllib.parse.quote(keyword)
for page in list(range(1, pages)):
response = requests.get('https://ecshweb.pchome.com.tw/search/v3.3/all/results?q=' + parse_word + '&page=' + str(page) + '&sort=rnk/dc')
raw_data = response.content.decode('utf-8')
data = json.loads(raw_data)
try:
myData = []
for product in data['prods']:
product_name = product['name']
prod_id = product['Id']
prod_price = product['price']
link = 'https://24h.pchome.com.tw/prod/' + prod_id
myData.append({
"名稱":product_name,
"價格":prod_price,
"網址":link
})
today = str(datetime.date.today())
fileName = today + '_' + keyword + '_Pchome.json'
try:
with open(fileName, 'a', encoding='utf-8') as f:
json.dump(myData, f, ensure_ascii=False, indent=4, skipkeys=True)
except Exception as err:
print(str(err))
except Exception as err:
print(str(err))
print('完成!')
</code></pre>
<p>而我的结果就在下面……这次是用双方括号……我做错什么了吗</p>
<pre><code>[
{
"名稱": "ASUS VivoBook Flip TP470EA-0112K1135G7 黑(i5-1135G7/8G/512G PCIe/Touch/Glare/W10/FHD/14)",
"價格": 27900,
"網址": "https://24h.pchome.com.tw/prod/DHAFLY-A900BKJJV"
}
][
{
"名稱": "ASUS VivoBook Flip TP470EA-0112K1135G7 黑(i5-1135G7/8G/512G PCIe/Touch/Glare/W10/FHD/14)",
"價格": 27900,
"網址": "https://24h.pchome.com.tw/prod/DHAFLY-A900BKJJV"
},
{
"名稱": "ASUS X515JF-0281G1035G1 星空灰(i5-1035G1/8G/MX130-2G/512G PCIe/W10/FHD/15.6)",
"價格": 23900,
"網址": "https://24h.pchome.com.tw/prod/DHAFL9-A900BLVZR"
}
][
{
"名稱": "ASUS VivoBook Flip TP470EA-0112K1135G7 黑(i5-1135G7/8G/512G PCIe/Touch/Glare/W10/FHD/14)",
"價格": 27900,
"網址": "https://24h.pchome.com.tw/prod/DHAFLY-A900BKJJV"
},
{
"名稱": "ASUS X515JF-0281G1035G1 星空灰(i5-1035G1/8G/MX130-2G/512G PCIe/W10/FHD/15.6)",
"價格": 23900,
"網址": "https://24h.pchome.com.tw/prod/DHAFL9-A900BLVZR"
},
{
"名稱": "ASUS X515MA-0471GN4120 星空灰(Celeron N4120/4G/256G PCIe/W10/FHD/15.6)",
"價格": 14900,
"網址": "https://24h.pchome.com.tw/prod/DHAFM4-A900BL8H7"
}
</code></pre>
<p>这是我的json文件中的一个示例的图像</p>
<p><a href="https://i.stack.imgur.com/Zl84M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zl84M.png" alt="Sample from JSON file"/></a></p>