Skip to main content
 首页 » 编程设计

python之在 bash 脚本中使用 python 函数之解析 JSON

2024年11月01日10dflying

我有一个 bash 脚本,旨在解析 JSON 格式的数据。我从这个论坛上的早期查询中了解到 bash 不擅长解析 JSON,因此打算使用 python 函数来进行解析:

以下是代码片段:

#!/bin/bash 
 
set -e 
 
declare -a data_id 
declare -a data_tid 
 
function parse_data () { 
    python <<EOF 
import json 
parsed = json.loads('''${@}''') 
 
data_id = [] 
data_tid = [] 
for child in parsed['params']['children'][0]: 
    print 'id: %s' % (child['data']['id']) 
    data_id.append(child['data']['id']) 
    print 'tid: %s' % (child['data']['tid']) 
    data_tid.append(child['data']['tid']) 
EOF 
} 
 
json=$(get_json_output) 
parse_data $json 

存储在“json”中的数据如下所示:

{ 
    "cid": "1", 
    "code": null, 
    "error": null, 
    "params": { 
        "children": [ 
            { 
                "value": { 
                    "id": "0123456789", 
                    "tid": "a.b.c" 
                }, 
                "data": { 
                    "id": "0987654321", 
                    "tid": "p.q.r" 
                }, 
                "tid": "m.n.o.p", 
            } 
        ], 
        "tid": "m.n.o.p" 
    }, 
    "reason": null, 
    "result": true 
} 

我希望脚本能够将“数据”下的“id”和“tid”字段提取到单独的数组中。但是脚本执行失败如下:

root@ubuntu# ./abc.sh  
Traceback (most recent call last): 
  File "<stdin>", line 7, in <module> 
TypeError: string indices must be integers 

知道哪里出了问题吗?

请您参考如下方法:

离开[0]:

for child in parsed['params']['children']: 

否则您将遍历 children 列表中第一个条目的键。

或者,如果该列表中只有一个条目,则不要循环,而是直接分配:

child = parsed['params']['children'][0] 
print 'id: %s' % (child['data']['id']) 
port_id.append(child['data']['id']) 
print 'tid: %s' % (child['data']['tid']) 
port_tid.append(child['data']['tid'])