0

How do I convert these two text strings into separate json objects

Text strings:

start process: Mon May 15 03:14:09 UTC 2017
logfilename: log_download_2017

Json output:

{
"start process": "Mon May 15 03:14:09 UTC 2017",
}
{
"logfilename": "log_download_2017",
}

Shell script:

logfilename="log_download_2017"
echo "start process: $(date -u)" | tee -a $logfilename.txt | jq -R split(:) >> $logfilename.json
echo "logfilename:" $logfilename | tee -a $logfilename.txt | jq -R split(:) >> $logfilename.json
Gabe
  • 226
  • 3
  • 13

1 Answers1

1

One approach would be to use index/1, e.g. along these lines:

jq -R 'index(":") as $ix | {(.[:$ix]) : .[$ix+1:]}'

Or, if your jq supports regex, you might like to consider:

jq -R 'match( "([^:]*):(.*)" ) | .captures | {(.[0].string): .[1].string}'

or:

jq -R '[capture( "(?<key>[^:]*):(?<value>.*)" )] | from_entries'
peak
  • 105,803
  • 17
  • 152
  • 177
  • Thank you, really helpful to see a number of approaches which enabled me to read the jq documentation more easily. I went with the first approach and that worked for all of my simple text string cases such as variable declarations. Next is lists and arrays, but will open a new question to deal with some example cases. Thanks again, it was great to have code options that work and can test. – Gabe May 15 '17 at 18:03
  • @Gabe - Glad to know that having some options has been helpful. Have you read http://stackoverflow.com/help/someone-answers ? – peak May 15 '17 at 18:44