1

I have a json containing day names as keys and I'm trying to select the value from the json using today as a key, where today is Thursday. However this does not work as intended.

SELECT hoursJson->'normalHours'->'Thursday' FROM BusinessHours;

returns the hours contained in the json correctly, but

SELECT hoursJson->'normalHours'->to_char(current_date, 'Day') FROM BusinessHours;

returns nothing.

Why is to_char(current_date, 'Day') not equal to 'Thursday' when used as a json key? to_char() returns text so I don't know why these two keys aren't equal. How do I make them equal so I can use to_char() as a json key?

Thanks!

4
  • It is working on 9.4. Can you send some examples? You can check a parenthesis: SELECT jsonval->'xxx'->(func())' Commented Feb 6, 2015 at 5:54
  • I'm on 9.3, unfortunately. Commented Feb 6, 2015 at 6:18
  • @PavelStehule No it isn't working in 9.4, to_char blank-pads the return value when you use 'Day' so ...->to_char(current_date, 'Day') will only work properly on Wednesday (in an English locale too of course). Commented Feb 6, 2015 at 6:34
  • @muistooshort I was partially wrong - I tested a usage of function there, not tested to_char( 'Day') Commented Feb 6, 2015 at 6:48

1 Answer 1

2

You have a whitespace problem. From the fine to_char manual:

Day full capitalized day name (blank-padded to 9 chars)

Note the "blank-padded" part. You're not getting 'Thursday' from to_char, you're getting 'Thursday ' and those are different keys in JSON.

If you want to keep using to_char then you're going to have to deal with the trailing whitespace using something like:

...->trim(trailing ' ' from to_char(current_date, 'Day'))
...->regexp_replace(to_char(current_date, 'Day'), '\s+', '')

A quick demo of what's going on (which will work on Thursday or Friday):

http://sqlfiddle.com/#!15/2a77b/23

You might want to use different keys in your JSON so that you won't have to deal with the whitespace at all or you could write your own function to hide away the to_char and trim nastiness.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked thanks! I'm using the trim method. Which one is more efficient?
@Teboto Probably trim but the difference is mostly likely too small to make any difference. Switching to day numbers in the JSON would be even better and would be locale-independent.

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.