2

I need to replace the following text:

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

with

"name": "abc1234", age: "24"
4
  • 1
    post the full json content OR a testable fragment Dec 19, 2017 at 16:14
  • 2
    what's the rule of replacement? should it cut the digits from existing value abc1234 OR just replace with static string abc? Post a valid object notation Dec 19, 2017 at 16:25
  • 1
    I don't see why this question got these many upvotes.. no code/research effort shown, only one sample line given without explanation.. should entire line be matched? only "name":[...] and so on...
    – Sundeep
    Dec 20, 2017 at 5:44
  • The document in the question is not a JSON document. It is missing enclosing curly braces, and the age key is not quoted.
    – Kusalananda
    Oct 16, 2022 at 21:13

4 Answers 4

13

If I understand correctly, you want do replace the "name" list by its first element. If this is the case try a Json processor:

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

(adaptations to the unpost full example may be needed)

0
7

The general answer is

man 7 regex

but specifically

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

or

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

Another option would be using the Python JSON module as in this SO answer. Here's a simple example:

  • 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)
    
  • Output

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

Assuming that the JSON document is well-formed and that the two keys name and age are top-level keys, as in

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

... then we may use jq to replace the value of the name key with the first element of the array:

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

If the input is an array of similar elements, as in

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

Then map the operation to each element:

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .