Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json_extract_array_element_text for strings #3

Open
mbrackett opened this issue Aug 3, 2019 · 2 comments
Open

json_extract_array_element_text for strings #3

mbrackett opened this issue Aug 3, 2019 · 2 comments

Comments

@mbrackett
Copy link

Compare:
select json_extract_array_element_text('["Sandwich", "Omelette", "Tikka Masala"]', 0)

In Redshift, that gets you an unquoted Sandwich, in docker-pgredshift that gets you a double-quoted "Sandwich".

Adding .strip('"') to the json.dumps seems to solve it:

CREATE FUNCTION json_extract_array_element_text(json_array text, array_index int) RETURNS text immutable as $$
    import json
    result = json.loads(json_array)[array_index]
    return json.dumps(result).strip('"')
    $$ LANGUAGE plpythonu;
@mbrackett
Copy link
Author

Similar issue in json_extract_path_text, as well as a missing for loop there

CREATE FUNCTION json_extract_path_text(json_string text, VARIADIC path_elems character[]) RETURNS text immutable as $$
    import json
    result = json.loads(json_string)
    for path_elem in path_elems:
        if path_elem not in result: return ""
        result = result[path_elem]
    return json.dumps(result).strip('"')
    $$ LANGUAGE plpythonu;

@shawnpyle
Copy link

In addition to a strip on the returning values, a check that the index is valid is needed.

CREATE OR REPLACE FUNCTION json_extract_array_element_text(json_array text, array_index int) RETURNS text immutable as $$
	import json
	items = json.loads(json_array)
	if 0 <= array_index and array_index < len(items):
		return json.dumps(items[array_index]).strip('"')
	else:
		return None
	$$ LANGUAGE plpythonu;

shawnpyle added a commit to shawnpyle/docker-pgredshift that referenced this issue Jan 18, 2022
Redshift returns NULL when a value cannot be found.
Redshift strips quotes from strings returned in the JSON.
Redshift checks for valid index when using json_extract_array_element_text.
shawnpyle added a commit to shawnpyle/docker-pgredshift that referenced this issue Jan 18, 2022
Redshift returns NULL when a value cannot be found.
Redshift strips quotes from strings returned in the JSON.
Redshift checks for valid index when using json_extract_array_element_text.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants