0

I can't figure out what is the problem with my following bash script:

#!/bin/bash

function jsonValue() {
    key=$1
    num=$2
    awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$key'\042/){print $(i+1)}}}' | tr -d '"' | sed -n ${num}p
}

json='{"_id": "dummy_id","title": "dummy_title"}'
id=$(echo $json | jsonValue _id)
title=$(echo $json | jsonValue title)

echo ${id}/${title}

The result is:

dummy_id title/ dummy_title

The function result does not contain space. Have you any idea what is the problem with the function?

Döme
  • 835
  • 11
  • 23
  • 1
    You didn't include a space in FS, so the field is `' "dummy_title"'` (with a leading space). – William Pursell Nov 30 '21 at 19:20
  • 1
    Seems like a job for `jq`. – choroba Nov 30 '21 at 19:30
  • 1
    You should copy/paste that script into http://shellcheck.net and fix the issues it'll tell you about. See also [how-do-i-use-shell-variables-in-an-awk-script](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script). – Ed Morton Nov 30 '21 at 19:39
  • 1
    What will you do when you have `json='{"_id": "1", "title": "this, is; a \"title\" {1}"}'`? – KamilCuk Nov 30 '21 at 19:50

1 Answers1

1

Have you any idea what is the problem with the function?

The problem is that your parser is very very poor and does not handle JSON strings with any spaces between : and beginning of the value. It also does not handle embedded , ; " in the values.

Do not reinvent the wheel - JSON is a well known format. Use tools and libraries designed to handle JSON. Use jq, use Python or Perl.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • You are right, normally I use jq for that, but I got an only bash env to solve a problem, so i am not able to install it. This function could be sufficient for only this job. – Döme Nov 30 '21 at 20:04
  • 1
    For 10000% you have perl, but also https://github.com/step-/JSON.awk – KamilCuk Nov 30 '21 at 20:05
  • @KamilCuk : _"Use jq, use Python or Perl"_ **or Ruby** :-D – Fravadona Nov 30 '21 at 20:27