1

I have a JSON that I am trying to process. I am using jq and can't for my life get the required output.

I have a simple eg below,

{
    "message" :"{ \"foo\": \"42\", \"bar\": \"less interesting data\"}"

}

My Build Up

jq '."message"

{
   "message" :{"foo": "42", "bar": "less interesting data"}
}

gives

{
  "foo": "42",
  "bar": "less interesting data"
}

."message"."bar"

gives

"less interesting data"

So

{
   "message" :"{"foo": "42", "bar": "less interesting data"}"
}

FAILS as JSON invalid

{
   "message" :"{\"foo\": \"42\", \"bar\": \"less interesting data\"}"
}

FAILS 'jq: error (at :3): Cannot index string with string "bar" exit status 5'

I have tried a whole bunch of differing jq queries (i won't waste your time listing them)

So I would like some advice on how id get "bar" from the JSON

It's not a duplicate of convert string to JSON as this leads you to the idea of conversion. Without this question, you'd never know the answer is to use fromjson

BobMonk
  • 178
  • 1
  • 10
  • 1
    Possible duplicate of [Convert string to json in jq](https://stackoverflow.com/questions/34340549/convert-string-to-json-in-jq) – oguz ismail Oct 12 '18 at 11:56
  • Its not a duplicate as this leads you to the idea of conversion to a string. Without this question, youd never know the answer is to use fromjson – BobMonk Oct 12 '18 at 13:30

1 Answers1

4

Use the fromjson construct to restore the strings as JSON texts. So, given the content below

{
    "message": "{ \"foo\": \"42\", \"bar\": \"less interesting data\" }"
}

all you need to do to extract bar is

jq '."message"|fromjson|.bar' file
"less interesting data"

To print the output without the quotes, use the -r/--raw-ouput flag which emits text in raw format. As noted in the comments fromjson.bar should also work as expected.

peak
  • 105,803
  • 17
  • 152
  • 177
Inian
  • 80,270
  • 14
  • 142
  • 161