I need to replace the following text:
"name":["abc1234"], age:"24"
with
"name": "abc1234", age: "24"
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIf 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)
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
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'}
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"
}
]
abc1234
OR just replace with static stringabc
? Post a valid object notation"name":[...]
and so on...age
key is not quoted.