从文本文件中替换 JSON 中的特定字段

Replacing specific fields in JSON from text file

我有一个 json 结构,想替换单独文本文件中 2 个字段中的字符串。

这是包含 2 条记录的 json 文件:

{
  "events" : {
    "-KKQQIUR7FAVxBOPOFhr" : {
      "dateAdded" : 1487592568926,
      "owner" : "62e6aaa0-a50c-4448-a381-f02efde2316d",
      "type" : "boycott"
    },
    "-KKjjM-pAXvTuEjDjoj_" : {
      "dateAdded" : 1487933370561,
      "owner" : "62e6aaa0-a50c-4448-a381-f02efde2316d",
      "type" : "boycott"
    }
  },
  "geo" : {
    "-KKQQIUR7FAVxBOPOFhr" : {
      ".priority" : "qw3yttz1k9",
      "g" : "qw3yttz1k9",
      "l" : [ 40.762632, -73.973837 ]
    },
    "-KKjjM-pAXvTuEjDjoj_" : {
      ".priority" : "qw3yttx6bv",
      "g" : "qw3yttx6bv",
      "l" : [ 41.889019, -87.626291 ]
    }
  },
  "log" : "null",
  "users" : {
    "62e6aaa0-a50c-4448-a381-f02efde2316d" : {
      "events" : {
        "-KKQQIUR7FAVxBOPOFhr" : {
          "type" : "boycott"
        },
        "-KKjjM-pAXvTuEjDjoj_" : {
          "type" : "boycott"
        }
      }
    }
  }
}

这是我要替换的 txt 文件:

49.287130, -123.124026
36.129770, -115.172811

还有很多记录,但为简洁起见,我将其保留为 2。

如有任何帮助,我们将不胜感激。谢谢。

问题描述似乎假定 JSON 对象中键值对的顺序是固定的。不同的面向 JSON 的工具(实际上是不同版本的 jq)对此有不同的看法。在任何情况下,以下假设 jq 的版本遵守顺序(例如 jq 1.5);它还假定 inputs 可用,尽管那是无关紧要的。

以下解决方案的关键是辅助函数map_nth_value/2,它修改JSON对象中第n个键的值:

def map_nth_value(n; filter):
  to_entries
  | (.[n] |= {"key": .key, "value": (.value | filter)} )
  | from_entries ;

[inputs | select(length > 0) | split(",") | map(tonumber)] as $lists
| reduce range(0; $lists|length) as $i
    ( $object;
      .geo |= map_nth_value($i; .l = $lists[$i] ) )

将上面的 jq 程序放在一个文件中(比如 program.jq),将文本文件放在一个文件中(比如 input.txt),将 JSON 对象放在一个文件中(说 object.json),以下调用:

jq -R -n --argfile object object.json -f program.jq input.txt

产生:

{
  "events": {
    "-KKQQIUR7FAVxBOPOFhr": {
      "dateAdded": 1487592568926,
      "owner": "62e6aaa0-a50c-4448-a381-f02efde2316d",
      "type": "boycott"
    },
    "-KKjjM-pAXvTuEjDjoj_": {
      "dateAdded": 1487933370561,
      "owner": "62e6aaa0-a50c-4448-a381-f02efde2316d",
      "type": "boycott"
    }
  },
  "geo": {
    "-KKQQIUR7FAVxBOPOFhr": {
      ".priority": "qw3yttz1k9",
      "g": "qw3yttz1k9",
      "l": [
        49.28713,
        -123.124026
      ]
    },
    "-KKjjM-pAXvTuEjDjoj_": {
      ".priority": "qw3yttx6bv",
      "g": "qw3yttx6bv",
      "l": [
        36.12977,
        -115.172811
      ]
    }
  },
  "log": "null",
  "users": {
    "62e6aaa0-a50c-4448-a381-f02efde2316d": {
      "events": {
        "-KKQQIUR7FAVxBOPOFhr": {
          "type": "boycott"
        },
        "-KKjjM-pAXvTuEjDjoj_": {
          "type": "boycott"
        }
      }
    }
  }
}