awk将配置文件转换为json

时间:2012-10-31 18:31:55

标签: json shell awk scripting-language

我有一个像这样的配置文件:

[sectionOne]
key1_1=value1_1
key1_n=value1_n


#this is a comment
[sectionTwo]
key2_1=value2_1
key2_n=value2_n

;this is a comment also
[SectionThree]
key3_1=value3_1
key3_n=value3_n
[SectionFor]
...

我需要使用最小的shell工具(没有perl,python,php,只是sed,awk可用)将其转换为json。

所需的输出是:

[
{"sectionOne": { "key1_1": "value1_1","key1_n": "value1_n"} },
{"sectionTwo": { "key2_1": "value2_1","key2_n": "value2_n"} },
{"sectionThree": { "key3_1": "value3_1","key3_n": "value3_n"}}
....
]

我尝试了几种方式/小时,没有成功

提前谢谢

3 个答案:

答案 0 :(得分:1)

您的样本输入和所需输出之间存在一些不一致,因此很难确定,但如果不是100%您想要的话,这应该很接近并且很容易调整:

$ cat file
[sectionOne]
key1_1=value1_1
key1_n=value1_n


#this is a comment
[sectionTwo]
key2_1=value2_1
key2_n=value2_n

;this is a comment also
[SectionThree]
key3_1=value3_1
key3_n=value3_n
$
$ cat tst.awk
BEGIN{
   FS="="
   print "["
}

/^([#;]|[[:space:]]*$)/ {
   next
}

gsub(/[][]/,"") {
   printf "%s{\"%s\": { ", rs, $0
   rs="} },\n"
   fs=""
   next
}

{
   printf "%s\"%s\": \"%s\"", fs, $1, $2
   fs=","
}

END{
   print rs "]"
}
$
$ awk -f tst.awk file
[
{"sectionOne": { "key1_1": "value1_1","key1_n": "value1_n"} },
{"sectionTwo": { "key2_1": "value2_1","key2_n": "value2_n"} },
{"SectionThree": { "key3_1": "value3_1","key3_n": "value3_n"} },
]

答案 1 :(得分:1)

awk 'BEGIN{ print "[" }
    /^[#;]/{ next }  # Ignore comments
    /^\[/{ gsub( "[][]", "" ); printf "%s{\"%s\": { ", s ? "}},\n" : "", $0; n=0; s=1 }
    /=/ { gsub( "=", "\":\"" ); printf "%c\"%s\" ", n ? "," : "", $0; n=1 }
    END{ print "}}\n]" }
' 

答案 2 :(得分:0)

以下是使用awk的bash解决方案:

#!/bin/bash

awk -F"=" 'BEGIN{in_section=0; first_field=0; printf "["}
            {
                last=length($1);
                if ( (substr($1,1,1) == "[") && (substr($1,last, last) == "]")) {
                    if (in_section==1) {
                        printf "} },";
                    }
                    section=substr($1, 2, last-2);
                    printf "\n{\"%s\":", section;
                    printf " {";
                    first_field=1;
                    in_section=1;
                } else if ( substr($1, 1, 1) == "#" || substr($1, 1, 1) == ";"){

                } else if ( ($1 != "") && ($2 != "") ) {
                    if (first_field==0) {
                        printf ", ";
                    }
                    printf "\"%s\": \"%s\"", $1, $2;
                    first_field=0;
                }

            }
            END{printf "} }\n]\n"}'