-1

I have a following string output.

{"uri":"/login-sessions","cookie":"sessionId=lhadasdfsdffdhjseodfjdksfjlsdjflsdjfldfjlsdf"}

I wanted to extract only "sessionId=lhadasdfsdffdhjseodfjdksfjlsdjflsdjfldfjlsdf" using sed and grep.

Tried the below command but i dont see any output

grep -`E ""cookie":"

Note : Above is a sting and not json dict. Not sure what needs to be done here. Can you help me out ?

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
Neil Roy
  • 17
  • 5

1 Answers1

1

It's not just a string but , and you need a json parser :

jq -r '.cookie' file.json

Output:

sessionId=lhadasdfsdffdhjseodfjdksfjlsdjflsdjfldfjlsdf

You can even manipulate content with this tool :

jq -r '.cookie = "foobar"' file.json

 Output

{
  "uri": "/login-sessions",
  "cookie": "foobar"
}
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I would not want to use jq app. I would want to do it with sed or grep. – Neil Roy Jan 08 '20 at 16:21
  • Why would you use a screwdriver to open a bean can ? jq is a standalone tool, no deps – Gilles Quénot Jan 08 '20 at 16:26
  • 2
    @NeilRoy, `sed` and `grep` don't know JSON. They'll get the details wrong if your string ever contains values that need quoting or escaping. For example, `sessionId=foo["bar"]` is represented in JSON as `"sessionId=foo[\"bar\"]"`, with extra quotes needed; similar special handling is needed for Unicode escapes, hex escapes, and various other nonprintables. Even if you don't have jq installed, the Python standard library is available everywhere and adequate-to-task; see answers on the linked duplicate. – Charles Duffy Jan 08 '20 at 16:35
  • 2
    @NeilRoy, ...moreover, `sed` and `grep` are line-oriented tools, but the JSON format *isn't* line-oriented. A JSON file can put `"cookie":` on one line and `"...your value..."` on the next line, and if your sed or grep code wasn't explicitly written to handle the case, it'll get wrong; alternately, it can have no whitespace outside of that included as literal content, and if your `sed` or `grep` code isn't written right, it'll get *that* wrong too. – Charles Duffy Jan 08 '20 at 16:39
  • 2
    @NeilRoy, ...I've had the misfortunate to build services used by customers who tried to parse and generate JSON by hand, and the reports for bugs that wouldn't exist if they used the right tools made my job hell (we couldn't modify our service even in ways that didn't change the semantics of the content, because of the fragility of our integration partners' tools). Don't be one of those people. – Charles Duffy Jan 08 '20 at 16:39