-2

I have json string like this

{"state":{"stateId":0,"nextPollingTime":null,"updateState":null},"config":{"privateIPs":null,"64Bit":false,"silent":false,"iid":14,"selfp":null,"sevlfp":null,"av":14,"aid":null,"aty":2,"sev":0,"seci":0,"sti":false,"scto":60000,"sci":5000,"stkd":5000,"sud":5000,"mpfa":3}}

I need to get "state" and "config" keys content to a shell custom variable or to a file.

tried with a command: $RESPONSE is the API response, the above json string

 echo $RESPONSE | sed 's/{"$state":"*\([0-9a-zA-Z]*\)"*,*.*}/\1/'

this prints nothing but suppose to get this output:

{"stateId":0,"nextPollingTime":null,"updateState":null} 

Tried with saving the response to tmp file and executed this command

cat /tmp/a.json | grep -o -e "{"state":.*}"

this also print empty string but expected result:

{"stateId":0,"nextPollingTime":null,"updateState":null} 

Am new to shell script and trying with various options available in the internet, please help me to write the command for the same.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    what do you mean by *`without any plugin`*? please update the question with the code you've tried, the (wrong) output generated by your code and the (correct) expected output, making sure both sets of output correspond to the provided input – markp-fuso Jan 27 '23 at 18:00
  • without any plugin meaning, installing tools like **jq** or any other similar ones. – nm-happy-to-code Jan 27 '23 at 18:14
  • I took a guess that you meant just using the mandatory POSIX tools (e.g. sed, awk, grep) and updated your subject to say that. If I guessed wrong then please change it to whatever you did mean as "without any plugin" is vague. – Ed Morton Jan 27 '23 at 18:18
  • 2
    (btw, `grep -o` is _itself_ a nonstandard extension; only the options described in https://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html are mandatory) – Charles Duffy Jan 27 '23 at 18:30
  • 1
    JSON *itself* is a non-POSIX format; why expect POSIX-standard tools to be sufficient or appropriate to work with it? – chepner Jan 27 '23 at 18:48
  • @CharlesDuffy https://github.com/step-/JSON.awk has some bugs and isn't itself POSIX compliant. I looked around the repo and can't see any way to contact the provider with suggestions, if you know how I could contact them, please let me know and I'll follow up with them. – Ed Morton Jan 27 '23 at 18:58

1 Answers1

3

This uses any sed:

$ sed 's/.*"state":\({[^}]*}\).*/\1/' file
{"stateId":0,"nextPollingTime":null,"updateState":null}

That will work for your posted input but fail given other json input (e.g. with "state" as a value or with } inside a value), just like any other solution that uses mandatory POSIX tools as none of them have a JSON parser (unless you write one with awk, but I expect that's more work than you or anyone here would put into this).

Ed Morton
  • 188,023
  • 17
  • 78
  • 185