如何将文本文件转换为 json 文件?

如何将文本文件转换为 json 文件?

我有一个包含以下内容的文本文件:

google.com,[email protected],[email protected]
latter.com,[email protected]

我正在尝试将此文本转换为 Json 格式,如下所示:

{
"domain": "google.com",
"emails":[{"email":"[email protected]","First":"xyz","Last":"pqr"},{"email":"[email protected]","First":"xyz","Last":"pqr"}]

}
{
"domain": "latter.com",
"emails":[{"email":"[email protected]","First":"xyz","Last":"pqr"}]
}

是否可以将此类文本转换为此类 JSON 格式?请告诉我。

答案1

快速而肮脏的 perl:

perl -MJSON -F, -lane '
    print encode_json({
        domain => shift @F, 
        emails => [map {{email => $_, First=>"xyz", Last=>"pqr"}} @F]
    })
' file

或者丑陋的 awk

awk -F, '{
    printf "{\"domain\":\"%s\",\"emails\":[", $1
    sep=""
    for (i=2; i<=NF; i++) {
        printf "%s{\"email\":\"%s\",\"First\":\"xyz\",\"Last\":\"pqr\"}", sep, $i
        sep=","
    }
    print "]}"
}' file 

答案2

@Jaffer Wilson 这是一个快速而肮脏的 bash 脚本,可能会对你有所帮助

function to_json() {
echo -en '{\n"domain":"'"$1"'",\n"emails":['
shift
EC=0
for EMAIL in "$@"
do
    echo -n '{"email":"'"$EMAIL"'","First":"xyz","Last":"pqr"}'
    EC=`expr "$EC" + 1`
    if [ "$EC" -ne "$#" ]; then
        echo -n ","
    fi
done
echo -e "]\n},"
}

while read LINE
do
    PARAMS=$(echo "$LINE" | tr "," " ")
    to_json "$PARAMS"
done

我将其保存为 convert_to_json.sh 并假设 data.txt 是文本所在的位置,将其运行为

$ chmod +x convert_to_json.sh
$ ./convert_to_json.sh < data.txt

相关内容