Skip to content
Mingtao edited this page Feb 18, 2019 · 2 revisions

Extract value from a json string

Input: "access_token":"abcdefg"

Output: abcdefg

General usage

sed 's/regexp/replacement/g'

Example 1

Replace access_token with blank

echo '{"access_token":"abcdefg"}' | sed 's/access_token//g'

{"":"abcdefg"}

Replace access_token with 123

echo '{"access_token":"abcdefg"}' | sed 's/access_token/123/g'

{"123":"abcdefg"}

Example 2

Replace "access_token": with blank. Note the double quotation doesn't need to be escaped

echo '{"access_token":"abcdefg"}' | sed 's/"access_token"://g'

{"abcdefg"}

Example 3

Replace {"access_token":" with blank. Note { could be anything. So we want to use a regular expression.

echo '{"access_token":"abcdefg"}' | sed 's/.*"access_token":"//g'

abcdefg"}

Example 4

Replace {"access_token":"abcdefg"} with blank. Note abcdefg and }should be represented by regular expression.

echo '{"access_token":"abcdefg"}' | sed 's/.*"access_token":".*".*//g'

< blank result >

Example 5

Replace {"access_token":"abcdefg"} with abcdefg.

echo '{"access_token":"abcdefg"}' | sed 's/.*"access_token":"\(.*\)".*/\1/g'

Here we wrap abcdefg with \(\), then use \1 to capture the value.

abcdefg

Example 6

Extract access_token's value from {"access_token":"abcdefg", "expire":"60"}

echo '{"access_token":"abcdefg", "expire":"60"}' | sed 's/.*"access_token":"\(.*\)".*/\1/g'

abcdefg", "expire":"60

It doesn't work because .* is 'greedy'. Replace \(.*\) with \([^"]*\)

echo '{"access_token":"abcdefg", "expire":"60"}' | sed 's/.*"access_token":"\([^"]*\)".*/\1/g'

abcdefg

[^"]* matches a string of non double quotation characters

Clone this wiki locally