在AWK中分离输出记录而不使用尾随分隔符

时间:2013-03-25 19:08:17

标签: json awk gawk nawk

我有以下记录:

31 Stockholm
42 Talin
34 Helsinki
24 Moscow
15 Tokyo

我想用AWK将它转换为JSON。使用此代码:

#!/usr/bin/awk
BEGIN {
    print "{";
    FS=" ";
    ORS=",\n";
    OFS=":";
};

{    
    if ( !a[city]++ && NR > 1 ) {
        key = $2;
        value = $1;
        print "\"" key "\"", value;
    }
};

END {
    ORS="\n";
    OFS=" ";
    print "\b\b}";
};

给我这个:

{
"Stockholm":31,
"Talin":42,
"Helsinki":34,
"Moscow":24,
"Tokyo":15, <--- I don't want this comma
}

问题是在最后一条数据行上尾随逗号。它使JSON输出不可接受。我怎样才能得到这个输出:

{
"Stockholm":31,
"Talin":42,
"Helsinki":34,
"Moscow":24,
"Tokyo":15
}

4 个答案:

答案 0 :(得分:9)

请注意您发布的脚本的一些反馈?

#!/usr/bin/awk        # Just be aware that on Solaris this will be old, broken awk which you must never use
BEGIN {
    print "{";        # On this and every other line, the trailing semi-colon is a pointless null-statement, remove all of these.
    FS=" ";           # This is setting FS to the value it already has so remove it.
    ORS=",\n";
    OFS=":";
};

{
    if ( !a[city]++ && NR > 1 ) {      # awk consists of <condition>{<action} segments so move this condition out to the condition part
                                       # also, you never populate a variable named "city" so `!a[city]++` won't behave sensibly.
        key = $2;
        value = $1;
        print "\"" key "\"", value;
    }
};

END {
    ORS="\n";                          # no need to set ORS and OFS when the script will no longer use them.
    OFS=" ";
    print "\b\b}";                     # why would you want to print a backspace???
};

因此您的原始脚本应该写成:

#!/usr/bin/awk
BEGIN {
    print "{"
    ORS=",\n"
    OFS=":"
}

!a[city]++ && (NR > 1) {    
    key = $2
    value = $1
    print "\"" key "\"", value
}

END {
    print "}"
}

以下是我真正编写脚本以将发布的输入转换为已发布的输出的方法:

$ cat file
31 Stockholm
42 Talin
34 Helsinki
24 Moscow
15 Tokyo
$
$ awk 'BEGIN{print "{"} {printf "%s\"%s\":%s",sep,$2,$1; sep=",\n"} END{print "\n}"}' file
{
"Stockholm":31,
"Talin":42,
"Helsinki":34,
"Moscow":24,
"Tokyo":15
}

答案 1 :(得分:2)

你有几个选择。当你要写出一个新行时,一个简单的方法是添加上一行的逗号:

  • first = 1中设置变量BEGIN

  • 当要打印一行时,请检查first。如果是1,则只需将其设置为0即可。如果0打印出逗号和换行符:

    if (first) { first = 0; } else { print ","; }
    

    这一点是为了避免在列表的开头添加额外的逗号。

  • 使用printf("%s", ...)代替print ...,以便在打印记录时可以避免换行。

  • 在大括号前添加额外的换行符,如:print "\n}";

另外,请注意,如果你不关心美学,JSON并不需要在项目等之间换行。你可以为整个辣酱玉米饼馅输出一条大线。

答案 2 :(得分:1)

您应该使用 json parser ,但这里是awk的方法:

BEGIN {
    print "{"    
}
NR==1{
    s= "\""$2"\":"$1
    next
}
{
    s=s",\n\""$2"\":"$1
}
END {
    printf "%s\n%s",s,"}"
}

输出:

{
"Stockholm":31,
"Talin":42,
"Helsinki":34,
"Moscow":24,
"Tokyo":15
}

答案 3 :(得分:0)

为什么不使用json解析器?不要强迫awk做某事并不是不可行的。以下是使用python的解决方案:

import json

d = {}
with open("file") as f:
    for line in f:
       (val, key) = line.split()
       d[key] = int(val)

print json.dumps(d,indent=0)

输出:

{
"Helsinki": 34, 
"Moscow": 24, 
"Stockholm": 31, 
"Talin": 42, 
"Tokyo": 15
}