0

I'm trying to put a JSON format to a file with one column, to do this I thought that awk can be a great tool.My input is (for example):

a
b
c
d
e

And my output that I want is:

{nodes:[{id='a'},
{id='b'},
{id='c'},
{id='d'},
{id='e'}]}

I tried with two different codes. The first one is:

BEGIN{
FS = "\t"
printf "{nodes:["
}
{printf "{'id':'%s'},\n",$1}
END{printf "{'id':'%s'}]}\n",$1}

But I print twice the last line:

{nodes:[{id='a'},
{id='b'},
{id='c'},
{id='d'},
{id='e'},
{id='e'}]}

The other option that I tried is with getline:

BEGIN{
FS = "\t"
printf "{nodes:["
}
{printf getline==0 ? "{'id':'%s'}]}" : "{'id':'%s'},\n",$1}

But for some reason, getline is always 1 instead to be 0 in the last line, so:

{nodes:[{id='a'},
{id='b'},
{id='c'},
{id='d'},
{id='e'},

Any suggestion to solve my problem?

oscarcapote
  • 417
  • 1
  • 4
  • 16
  • 1
    This may help: http://stackoverflow.com/questions/11866860/how-do-you-skip-the-last-line-w-awk – Ruud Helderman Apr 04 '17 at 09:50
  • 2
    You dont use a valide json format. Every name and value needs to be surrounded by quotes `"`, except numbers and boolean values. You should use the tool `jq` to verify your json-data. Do it has to be `awk`, or can you create a simple `echo` with all the stuff in it ? – Mario Apr 04 '17 at 09:53
  • Both have reason, now my code works – oscarcapote Apr 04 '17 at 10:02

3 Answers3

1

In awk. Buffer the output to variable b and process it before outputing:

$ awk 'BEGIN{b="{nodes:["}{b=b "{id=\x27" $0 "\x27},\n"}END{sub(/,\n$/,"]}",b);print b}' file
{nodes:[{id='a'},
{id='b'},
{id='c'},
{id='d'},
{id='e'}]}

Explained:

BEGIN { b="{nodes:[" }                  # front matter
      { b=b "{id=\x27" $0 "\x27},\n" }  # middle 
END   { sub(/,\n$/,"]}",b); print b }   # end matter and replace ,\n in the end
                                        # with something more appropriate
James Brown
  • 36,089
  • 7
  • 43
  • 59
0

Solution (thanks to @Ruud and @suleiman)

BEGIN{
FS = "\t"
printf "{'nodes':["
}
NR > 1{printf "{'id':'%s'},\n",prev}
{prev = $1}
END{printf "{'id':'%s'}]}",prev}
oscarcapote
  • 417
  • 1
  • 4
  • 16
0

Try this -

$awk -v count=$(wc -l < f) 'BEGIN{kk=getline;printf "{nodes:[={'id':'%s'},\n",$kk}
> {
> if(NR < count)
> {
> {printf "{'id':'%s'},\n",$1}
> }}
> END{printf "{'id':'%s'}]}\n",$1}' f
{nodes:[={id:a},
{id:b},
{id:c},
{id:d},
{id:e}]}
VIPIN KUMAR
  • 3,019
  • 1
  • 23
  • 34