繁体   English   中英

如何从 JSON 中获取值

[英]How to get a value from JSON

这是我第一次使用 JSON,我试图从下面的 JSON 中提取url

{
    "name": "The_New11d112a_Company_Name",
    "sections": [
        {
            "name": "Products",
            "payload": [
                {
                    "id": 1,
                    "name": "TERi Geriatric Patient Skills Trainer,
                    "type": "string"
                }
            ]
        },
        {
            "name": "Contact Info",
            "payload": [
                {
                    "id": 1,
                    "name": "contacts",
                    "url": "https://www.a3bs.com/catheterization-kits-8000892-3011958-3b-scientific,p_1057_31043.html",
                    "contacts": [
                        {
                        "name": "User",
                        "email": "Company Email",
                        "phone": "Company PhoneNumber"
                    }
                ],
                "type": "contact"
            }
        ]
    }
],
"tags": [
    "Male",
    "Airway"
],
"_id": "0e4cd5c6-4d2f-48b9-acf2-5aa75ade36e1"

}

我已经能够通过访问description_id

data = json.loads(line)
        if 'xpath' in data:
            xpath = data["_id"]
            description = data["sections"][0]["payload"][0]["description"]

但是,我似乎无法找到访问url 另外一个问题,我已经是有可能在其他项目sections ,这使得置入到Contact Info非首发。

希望这可以帮助:

import json

with open("test.json", "r") as f:
    json_out = json.load(f)
    for i in json_out["sections"]:
        for j in i["payload"]:
            for key in j:
                if "url" in key:
                    print(key, '->', j[key])

我认为您的JSON已损坏,应该是这样。

{
    "name": "The_New11d112a_Company_Name",
    "sections": [
        {
            "name": "Products",
            "payload": [
                {
                    "id": 1,
                    "name": "TERi Geriatric Patient Skills Trainer",
                    "type": "string"
                }
            ]
        },
        {
            "name": "Contact Info",
            "payload": [
                {
                    "id": 1,
                    "name": "contacts",
                    "url": "https://www.a3bs.com/catheterization-kits-8000892-3011958-3b-scientific,p_1057_31043.html",
                    "contacts": [
                        {
                        "name": "User",
                        "email": "Company Email",
                        "phone": "Company PhoneNumber"
                    }
                ],
                "type": "contact"
            }
        ]
    }
],
"tags": [
    "Male",
    "Airway"
],
"_id": "0e4cd5c6-4d2f-48b9-acf2-5aa75ade36e1"
}

您可以在http://json.parser.online.fr/上查看。

如果你想获取 url 的值。

import json
j = json.load(open('yourJSONfile.json'))
print(j['sections'][1]['payload'][0]['url'])

我认为值得编写一个简短的函数来获取url(s) ,并决定是否使用返回列表中第一个找到的url ,或者如果您的数据中没有可用的 url,则跳过处理。

该方法应如下所示:

def extract_urls(data):
    payloads = []
    for section in data['sections']:
        payloads += section.get('payload') or []

    urls = [x['url'] for x in payloads if 'url' in x]

    return urls

这应该打印出 URL

import json
# open json file to read
with open('test.json','r') as f:
    # load json, parameter as json text (file contents)
    data = json.loads(f.read())
    # after observing format of JSON data, the location of the URL key
    # is determined and the data variable is manipulated to extract the value
    print(data['sections'][1]['payload'][0]['url'])

'url' 键的确切位置:

数组的第一个(位置)是键“sections”的值

在数组值里面,有一个字典,key 'payload' 包含一个数组

在数组的第 0 个(位置)是一个带有键“url”的字典


在测试我的解决方案时,我注意到提供的 json 有缺陷,在修复 json 缺陷(3)后,我最终得到了这个。

{
"name": "The_New11d112a_Company_Name",
"sections": [
    {
        "name": "Products",
        "payload": [
            {
                "id": 1,
                "name": "TERi Geriatric Patient Skills Trainer",
                "type": "string"
            }
        ]
    },
    {
        "name": "Contact Info",
        "payload": [
            {
                "id": 1,
                "name": "contacts",
                "url": "https://www.a3bs.com/catheterization-kits-8000892-3011958-3b-scientific,p_1057_31043.html",
                "contacts": [
                    {
                    "name": "User",
                    "email": "Company Email",
                    "phone": "Company PhoneNumber"
                }
            ],
            "type": "contact"
        }
    ]
}
],
"tags": [
"Male",
"Airway"
],
"_id": "0e4cd5c6-4d2f-48b9-acf2-5aa75ade36e1"}

在使用 Vincent55 提供的 JSON 之后。 我做了一个带有异常处理和某些假设的工作代码。

工作代码:

## Assuming that the target data is always under sections[i].payload
from json import loads
line = open("data.json").read()
data = loads(line)["sections"]
for x in data:
    try:
        # With assumption that there is only one payload
        if x["payload"][0]["url"]:
            print(x["payload"][0]["url"])
    except KeyError:
        pass

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM