如何替换 JSON 文件中的元素?

如何替换 JSON 文件中的元素?

我需要替换以下文本:

"name":["abc1234"], age:"24" 

"name": "abc1234", age: "24"

答案1

如果我理解正确,您需要将“名称”列表替换为其第一个元素。如果是这种情况,请尝试 Json 处理器:

jq '.name=.name[0]' ex.json

(可能需要对 unpost 完整示例进行改编)

答案2

一般的答案是

man 7 regex

但具体来说

sed -E 's/"name":\["abc1234"\], age:"24" /"name": "abc1234", age:"24"/g' file > new

或者

sed -E 's/"name" *: *\["([^"]+)"\], *age *: *"([0-9]+)"/"name": "\1", age:"\2"/g' file > new
grep -E '"name" *: *\[' new

答案3

另一种选择是使用Python JSON 模块这个答案。这是一个简单的例子:

  • in.json

    { "name":["abc1234"], "age":"24" }
    
  • replaceInJson.py

    #!/usr/bin/python3
    
    import json
    
    with open("in.json", "r") as f:
        data = json.load(f)
        print("Before:", data)
        data["name"] = data["name"][0]
        print("After: ", data)
    
  • 输出

    Before: {'name': ['abc1234'], 'age': '24'}
    After:  {'name': 'abc1234', 'age': '24'}
    

答案4

假设 JSON 文档格式良好,并且两个键nameage是顶级键,如下所示

{
   "name": [ "abc1234" ],
   "age": "24"
}

...然后我们可以用数组的第一个元素jq替换键的值:name

$ jq '.name |= first' file
{
  "name": "abc1234",
  "age": "24"
}

如果输入是相似元素的数组,如

[
   {
      "age": "24",
      "name": [ "abc1234" ]
   },
   {
      "age": "24",
      "name": [ "abc1234" ]
   },
   {
      "age": "24",
      "name": [ "abc1234" ]
   },
   {
      "age": "24",
      "name": [ "abc1234" ]
   }
]

然后map对每个元素进行操作:

$ jq 'map(.name |= first)' file
[
  {
    "name": "abc1234",
    "age": "24"
  },
  {
    "name": "abc1234",
    "age": "24"
  },
  {
    "name": "abc1234",
    "age": "24"
  },
  {
    "name": "abc1234",
    "age": "24"
  }
]

相关内容