Wednesday 4 December 2019

json - Print before and after each record in awk

I am trying to convert LDIF to JSON using awk.




Can't figure out how to print before and after each multi-line record. Can print in BEGIN and END one time each or before and after each line. But never before and after each record.



Actual LDIF input to awk is:



dn: CN=foo
objectClass: top

dn: CN=bar
objectClass: top



To convert to JSON awk needs output to look like this:



{
"dn": "CN=foo",
"objectClass": "top"
}
{
"dn": "CN=bar",

"objectClass": "top"
}


Script 1 wraps each line of the record with curly braces.



BEGIN {                                                                                                                                                        
RS="\n\n#";
FS=": ";
}

print "{"
{
print "\""$1"\": \""$2"\",";
}
print "}"


Script 2 wraps the set of all records with on set of curly braces:



BEGIN {                                                                                                                                                        

RS="\n\n#";
FS=": ";
print "{"
}
{
print "\""$1"\": \""$2"\",";
}
END{
print "}"
}



Seems like awk only has BEGIN, END and implicit loop over records (single or multi-line). I can't figure out how to print something before and after each multi-line record. Is this possible in awk? Is there a better way to convert LDIF to JSON?



What would an awk script, not a one liner, look like that does the LDIF to JSON conversion?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...