简体   繁体   English

如何从 JSON 中获取值

[英]How to get a value from JSON

This is the first time I'm working with JSON, and I'm trying to pull url out of the JSON below.这是我第一次使用 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"

} }

I have been able to access description and _id via我已经能够通过访问description_id

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

However, I can't seem to figure out a way to access url .但是,我似乎无法找到访问url One other issue I have is there could be other items in sections , which makes indexing into Contact Info a non starter.另外一个问题,我已经是有可能在其他项目sections ,这使得置入到Contact Info非首发。

Hope this helps:希望这可以帮助:

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])

I think your JSON is damaged, it should be like that.我认为您的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"
}

You can check it on http://json.parser.online.fr/ .您可以在http://json.parser.online.fr/上查看。

And if you want to get the value of the url.如果你想获取 url 的值。

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

I think it's worth to write a short function to get the url(s) and make a decision whether or not to use the first found url in the returned list, or skip processing if there's no url available in your data.我认为值得编写一个简短的函数来获取url(s) ,并决定是否使用返回列表中第一个找到的url ,或者如果您的数据中没有可用的 url,则跳过处理。

The method shall looks like this:该方法应如下所示:

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

This should print out the URL这应该打印出 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'])

The exact location of the 'url' key: 'url' 键的确切位置:

1st (position) of the array which is the value of the key 'sections'数组的第一个(位置)是键“sections”的值

Inside the array value, there is a dict, and the key 'payload' contains an array在数组值里面,有一个字典,key 'payload' 包含一个数组

In the 0th (position) of the array is a dict with a key 'url'在数组的第 0 个(位置)是一个带有键“url”的字典


While testing my solution, I noticed that the json provided is flawed, after fixing the json flaws(3), I ended up with this.在测试我的解决方案时,我注意到提供的 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"}

After utilizing the JSON that was provided by Vincent55.在使用 Vincent55 提供的 JSON 之后。 I made a working code with exception handling and with certain assumptions.我做了一个带有异常处理和某些假设的工作代码。

Working Code:工作代码:

## 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