gpt4 book ai didi

json - 在没有尾随分隔符的情况下分隔 AWK 中的输出记录

转载 作者:行者123 更新时间:2023-12-04 17:01:44 29 4
gpt4 key购买 nike

我有以下记录:

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 输出 Not Acceptable 。我怎样才能得到这个输出:
{
"Stockholm":31,
"Talin":42,
"Helsinki":34,
"Moscow":24,
"Tokyo":15
}

最佳答案

介意对您发布的脚本的一些反馈吗?

#!/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
}

关于json - 在没有尾随分隔符的情况下分隔 AWK 中的输出记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622776/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com