Sunday, August 7, 2016

Extract the value of a field in a json file using just bash

I had a need to extract the value of a particular string field in a JSON file. There were a lot of files and I wanted to process them all so I could use that value in a bash script:

# arg: filename
# return: contents of file without \n
function build_file
    while read line
        str="$str $line"
    done < $1
    echo $str
# first arg: filename
# second arg: field
function extract_field
    text=`build_file $1`
    if [[ $text =~ $regex ]]; then
        echo ${BASH_REMATCH[1]}
        echo "$2 not found in $1"
# change this value to that of your field-name
for f in *.json; do
    echo `extract_field $f $field`

You run this script in a directory where there are .json files. It then prints out the value of that field (minus the quotes) or an error message. Change the "docid" line to the name of your desired field.

No comments:

Post a Comment