简体   繁体   中英

Convert string with delimiter to an array in Json using AWK

I have below style format json and I would like to convert the values in double quotes with delimiter comma to array of elements.

The json field I would like to convert is a part of huge Json file.

So I need to find the field

Convert

Before
{"name": "john, jane, gordon, matthew"} 

               to 
After    
{"field": ["john","jane","gordon", "matthew"]}

If your Json file has entries in a single line, then this AWK program works for your example:

{
    sub(": *",": [")
    sub("}","]}")
    gsub(", *","\",\"")
    print
}

If your data is in a single line, replace sub with gsub .

如果所有行的格式都相似,请尝试一下

 awk '{print gensub(/\"/,"[","3")}' | awk '{print gensub(/\"}$/,"]}","")}' filename

I think sed is also good like in this case

$ sed -r 's/"([^"]+)".*"([^"]+)"/{"\1": ["\2"]}/; s/ ?, ?/","/g' file
{{"name": ["john","jane","gordon","matthew"]}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM