gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:46 27 4
gpt4 key购买 nike

我有一个 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'])

关于python - 在 bash 脚本中使用 python 函数 - 解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20400905/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com