【问题标题】:Iterate over JSON Object using Python使用 Python 迭代 JSON 对象
【发布时间】:2019-05-12 18:14:28
【问题描述】:

我有一个 JSON 对象,想知道如何遍历该对象以提取“id”的值。

{
"totalSize": 5,
"done": true,
"records": [
    {
        "attributes": {
            "type": "EventLogFile",
            "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7dWAA"
        },
        "Id": "0AT1U000003kk7dWAA"
    },
    {
        "attributes": {
            "type": "EventLogFile",
            "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7eWAA"
        },
        "Id": "0AT1U000003kk7eWAA" 

我在下面尝试了一些东西。

sub_data = s["records"]["id"]
for i in sub_data:
        print(sub_data['id'])

【问题讨论】:

    标签: python json python-2.7


    【解决方案1】:
    s = """{ "totalSize": 5, 
            "done": true, "records": [ 
                { "attributes": { 
                    "type": "EventLogFile", 
                    "url": "/services/data/v38.0/sobjects/EventLogFile/0AT1U000003kk7dWAA" }, 
                    "Id": "0AT1U000003kk7dWAA" } 
            ] 
        }"""
    s = json.loads(s)
    
    [r['Id'] for r in s['records']]
    
    ['0AT1U000003kk7dWAA']
    

    【讨论】:

    • 您的解决方案似乎正确。只需遍历字典列表。猜猜,我仍然得到同样的错误。 s1 = [r['id'] for r in s['records']] TypeError: string indices must be integers, not str
    • @AshishLal 你能添加触发这个错误的 JSON 吗?
    • { "totalSize": 5, "done": true, "records": [ { "attributes": { "type": "EventLogFile", "url": "/services/data/ v38.0/sobjects/EventLogFile/0AT1U000003kk7dWAA" }, "Id": "0AT1U000003kk7dWAA" }, ] }
    • 它适用于我[r['Id'] for r in s['records']] 结果是['0AT1U000003kk7dWAA']
    • 我确信它有效。不知道为什么它不适合我
    【解决方案2】:

    您可以将records 键作为列表进行迭代,然后访问每个子字典的Id 键:

    for i in s["records"]:
        print(i['Id'])
    

    【讨论】:

    • 谢谢!。我确实尝试过并收到以下错误:for i in s["records"]: TypeError: string indices must be integers, not str
    • 很高兴能提供帮助。如果您认为此答案正确,您能否将其标记为已接受? (点击答案旁边的灰色复选标记。)
    猜你喜欢
    • 2013-09-19
    • 2017-07-05
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 2019-08-11
    • 2013-02-26
    • 2012-12-14
    相关资源
    最近更新 更多