You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多次追加的非有效JSON转换为含data数组的规范格式

问题描述

我通过运行script.sh脚本三次(分别执行./script.sh 1.1.1.1 17、./script.sh 1.1.1.1 17、./script.sh 1.1.1.1 10)向file.json插入数据,当前file.json内容为:

{
  "ip": "1.1.1.1",
  "tested_count": 17,
  "last_scan_date": "1673169149"
}
{
  "ip": "1.1.1.1",
  "tested_count": 17,
  "last_scan_date": "1673169159"
}
{
  "ip": "1.1.1.1",
  "tested_count": 10,
  "last_scan_date": "1673169326"
}

脚本实现如下:

#!/bin/bash

# I run this script 3 times to insert into file.json:

#./script.sh 1.1.1.1 17
#./script.sh 1.1.1.1 17
#./script.sh 1.1.1.1 10

OUTPUT='file.json'
JSON_OUTPUT='data:{}'

IP="$1"
TEST_COUNT="$2"

JSON_OUTPUT=$(jq \
  --arg ip "${IP}" \
  --argjson tested_count "${TEST_COUNT}" \
  --arg last_scan_date "$(date +%s)" \
  '{ip: $ip, tested_count: $tested_count, last_scan_date: $last_scan_date}' <<<"${JSON_OUTPUT}")

# Write the output to the file
echo "${JSON_OUTPUT}" >>"${OUTPUT}"

目前file.json是无效JSON,需要转换成以下规范格式:

{
  "data": [
    {
      "ip": "1.1.1.1",
      "tested_count": 17,
      "last_scan_date": "1673169149"
    },
    {
      "ip": "1.1.1.1",
      "tested_count": 17,
      "last_scan_date": "1673169159"
    },
    {
      "ip": "1.1.1.1",
      "tested_count": 10,
      "last_scan_date": "1673169326"
    }
  ]
}

我尝试过用echo "$json_query" | jq -n '.data |= [inputs]' >> file.json修复,但没解决问题,求可行方法。

解决方法

1. 修复现有无效JSON文件

直接用jq读取所有独立的JSON对象,将它们包裹到data数组中:

jq -n '{data: [inputs]}' file.json > fixed_file.json

执行完这个命令后,fixed_file.json就是你需要的规范格式。如果想直接覆盖原文件,可以用:

jq -n '{data: [inputs]}' file.json > temp.json && mv temp.json file.json

2. 修改脚本避免后续生成无效JSON

原来的脚本每次追加独立JSON对象导致格式错误,修改脚本让它维护一个有效的JSON数组:

#!/bin/bash

OUTPUT='file.json'
IP="$1"
TEST_COUNT="$2"

# 构造新的条目
new_entry=$(jq -n \
  --arg ip "${IP}" \
  --argjson tested_count "${TEST_COUNT}" \
  --arg last_scan_date "$(date +%s)" \
  '{ip: $ip, tested_count: $tested_count, last_scan_date: $last_scan_date}')

# 如果文件不存在,初始化带空数组的结构;否则追加新条目到数组
if [ ! -f "${OUTPUT}" ]; then
  echo '{"data": []}' > "${OUTPUT}"
fi

jq --argjson entry "${new_entry}" '.data += [$entry]' "${OUTPUT}" > temp.json && mv temp.json "${OUTPUT}"

这样每次运行脚本都会向data数组中添加新条目,始终保持file.json是有效的JSON格式。

内容的提问来源于stack exchange,提问作者Kalib Zen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:35:31