1

I've got a table field "data" with the following json:

[{"reason": "Other", "bla": 12345, "amount": "34.00", "moredata": [23, 22], "date": "2014-01-02T01:55:28.646364+00:00", "message": "Bla", "applied_to": "client"}]

And I'd like to get only the value of the json value of amount, so 34.00 in the case above in PostgreSQL.

So far I have:

substring(data from '%#"_amount_: ___.___#"%' for '#'),

Sadly this gives me "amount":"34.00", instead of just 34.00. It also doesn't work if the amount value is 9.00 or 102.00.

Any help would be appreciated.

1
  • Why not just use the built-in json support, which has a proper json parser? Or use a PL like plperl and a json lib for it? String-fiddling will be fragile and unreliable. Commented Jan 6, 2014 at 14:57

1 Answer 1

6

Try:

substring(data from '(?:"amount": ")([\d\.]*)')

See it working here and here's what it does:

NODE                     EXPLANATION
--------------------------------------------------------------------
  (?:                      group, but do not capture:
--------------------------------------------------------------------
    "amount": "              '"amount": "'
--------------------------------------------------------------------
  )                        end of grouping
--------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------
    [\d\.]*                  any character of: digits (0-9), '\.' (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------
  )                        end of \1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a million for this. I had to make a slight modification in my own case, to use '\w' instead of '\d' for all "word" characters instead of digits only. Also my JSON looked a wee bit different, so I had to remove the space and colon. Here's what mine looked like: "HasOptedOutOfEmail":false which I parsed using this regex '(?:"HasOptedOutOfEmail":)([\w\.]*)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.