gpt4 book ai didi

python - jq + 更新json文件并根据ID号附加名称

转载 作者:太空宇宙 更新时间:2023-11-04 05:07:45 26 4
gpt4 key购买 nike

我们要根据以下规则编辑json文件

我们需要在 mazda 字符串下生成名称 car0X_hyb.com(而 X 是 ID 号)

我们需要更新 Linux 机器上的 json 文件

示例 - ID=1

那么 json 将是这样

{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com"
],
"ford": [
"car01_eng.com"
]
}

ID=4 ,则 json 将为

{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com"
],
"ford": [
"car01_eng.com"
]
}

ID=6 ,则 json 将为

{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com",
"car06_hyb.com"
],
"ford": [
"car01_eng.com"
]
}

ID=10 ,则 json 将为

{
"toyota": [
"car1.com"
],
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com",
"car06_hyb.com",
"car07_hyb.com",
"car08_hyb.com",
"car09_hyb.com",
"car10_hyb.com"
],
"ford": [
"car01_eng.com"
]
}

最佳答案

您可以使用 range 生成后续数字流,使用它们填充模板字符串,并从结果中创建一个数组,例如:

$ jq -n --argjson ID 5 '.mazda = [ range($ID) | "car\("0\(.+1)"[-2:])_hyb.com" ]'
{
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com"
]
}
$ jq -n --argjson ID 10 '.mazda = [ range($ID) | "car\("0\(.+1)"[-2:])_hyb.com" ]'
{
"mazda": [
"car01_hyb.com",
"car02_hyb.com",
"car03_hyb.com",
"car04_hyb.com",
"car05_hyb.com",
"car06_hyb.com",
"car07_hyb.com",
"car08_hyb.com",
"car09_hyb.com",
"car10_hyb.com"
]
}

根据ID字符的最大长度调整前导0-2

关于python - jq + 更新json文件并根据ID号附加名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59077074/

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