从JSON文件刮擦数据

发布于 2025-02-01 08:37:52 字数 983 浏览 2 评论 0原文

我正在尝试从JSON文件刮擦 name ,但它们向我显示字符串索引必须是整数,如您所见 JSON文件:

 "prodBean": {
            "subProdTerms": null,
            "friendlyUrl": "/brakes-wheel-end/brake-drums-rotors/brake-drum/otr-brake-drum-otr1601b",
            "name": "OTR 16.5 x 7 Brake Drum, Balanced",
            "showSubscriptionSelection": false,
            "UnitOfMeasure": "EA",
            "qtyPerUnit": 1.0,
            "sequence": 2,
            "availMsg": null,
            "ProductStatus": "Released",
            "ProductType": "Product",
            "sku": "OTR-OTR1601B",
            "id": "a8G1W000000Y7DfUAK",
            "showNewSubscriptionSelection": false,
            "savings": 405.49,
            "basePrice": 405.492,
            "price": 0.0,
            "ECrossReferencesS"

代码

import json

with open("test.json","r") as file:
    temp=json.load(file)

for item in temp:
    title=item['prodBean']['name']
    print(title)

I am trying to scrape name from json file but they show me error that string indices must be integers as you see below json code
Json file:

 "prodBean": {
            "subProdTerms": null,
            "friendlyUrl": "/brakes-wheel-end/brake-drums-rotors/brake-drum/otr-brake-drum-otr1601b",
            "name": "OTR 16.5 x 7 Brake Drum, Balanced",
            "showSubscriptionSelection": false,
            "UnitOfMeasure": "EA",
            "qtyPerUnit": 1.0,
            "sequence": 2,
            "availMsg": null,
            "ProductStatus": "Released",
            "ProductType": "Product",
            "sku": "OTR-OTR1601B",
            "id": "a8G1W000000Y7DfUAK",
            "showNewSubscriptionSelection": false,
            "savings": 405.49,
            "basePrice": 405.492,
            "price": 0.0,
            "ECrossReferencesS"

Code

import json

with open("test.json","r") as file:
    temp=json.load(file)

for item in temp:
    title=item['prodBean']['name']
    print(title)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初相遇 2025-02-08 08:37:52

在您的情况下,加载语句返回dict。当您用单个参数迭代dict时,您只会得到键:

>>> for item in temp:
...     print(item)
...
prodBean

您需要使用.items()迭代dict,那么您将可以访问数据:

>>> for k, v in temp.items():
...     item = v['name']
...     print(item)
...
OTR 16.5 x 7 Brake Drum, Balanced

The load statement in your case returns a dict. When you iterate a dict with a single parameter, you get just the keys:

>>> for item in temp:
...     print(item)
...
prodBean

You need to iterate the dict with .items(), then you'll have access to the data:

>>> for k, v in temp.items():
...     item = v['name']
...     print(item)
...
OTR 16.5 x 7 Brake Drum, Balanced
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文