1

I would like to extract contents of field in file

the way data looks :

{"_index":"bk","_type":"account","_id":"1","_score":1,"_source":{"a_n":1,"firstname":"Blake","lastname":"Hess","age":30,"gender":"M","address":"anything Avenue","employer":"anything","email":"anything@gmail.com","city":"anything","state":"anything"}}

the desired output

Blake
  • are these 2 separate files ? or one file with one json string per line ? – pLumo Oct 21 at 11:56
5

Use jq to parse json data:

jq -r '._source.firstname'

With the input data from the question it shows the desired output.

  • tried jq -r .firstname bucket.json result is null , null , null etc.. – I'm V Oct 21 at 12:05
  • 1
    @I'mV I guess your file bucket.json doesn't contain the data shown in the question. Please show (a piece of) your real data. – Bodo Oct 21 at 12:13
  • @Bodo edited the question with real data – I'm V Oct 21 at 12:28
  • 1
    @I'mV Now corrected. – Kusalananda Oct 21 at 12:31
  • thanks Kusa ;-) – pLumo Oct 21 at 12:35
0

In principle, the dedicated JSON parsers mentioned are the right approach. If, for some reason, this doesn't work for you, and you really are only interested in this particular field value, then the following is a quick but dirty(!!) hack to extract the field value:

awk '{split($1,fld,"\"firstname\":\"[[:alnum:]]*\"",sep); print(sep[1])}' <filename> | sed -e "s/\"firstname\":\"//" -e "s/\"$//"

This basically uses the pattern "firstname":"<some string>" as field separator, prints the actual value of the field separator (which would be "firstname":"Blake" in your case), and pipes it through sed in order to remove the field label, leading double-quote and trailing double-quote.

Again, it is a dirty hack and a dedicated tool should be used whenever possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.