简体   繁体   English

尝试将 json 转换为字符串 (Athena AWS)

[英]Trying to convert json to string (Athena AWS)

I have a json formatted like: myjson = {"key":["value1","value2"]} and a I want to convert it as string我有一个 json 格式如下: myjson = {"key":["value1","value2"]}我想将它转换为字符串
Sometime this json can return null: myjson = {"key":null} .有时这个 json 可以返回 null: myjson = {"key":null}

I want to get the values as a string, but I get an error when I try to cast cast(json_extract(myjson,'$.key') as varchar) .我想获取字符串形式的值,但是当我尝试将cast(json_extract(myjson,'$.key') as varchar)时出现错误。 The error says that is not possible to convert '["value1","value2"]' to varchar.该错误表明无法将 '["value1","value2"]' 转换为 varchar。 I think it is because of the double quote.我认为这是因为双引号。 I need help to work around this problem.我需要帮助来解决这个问题。

Edit1:编辑1:

  • The output of json_extract(myjson,'$.key') is a json object; json_extract(myjson,'$.key')的output是一个json object;
  • I want to get a string like 'value1, value2' or 'null'我想得到一个像 'value1, value2' 或 'null' 这样的字符串
  • At the moment I do not know how to verify if it is null or not目前我不知道如何验证它是否是 null

You can use json_format (though depending on the following usage leaving just json_extract without cast/format/etc. can be fine in some cases):您可以使用json_format (尽管取决于以下用法,只留下json_extract而没有 cast/format/等。在某些情况下可能没问题):

-- sample data
with dataset(json_str) as (
    values ('{"key":["value1","value2"]}'),
        ('{"key":null}')
)

-- query
select json_format(json_extract(json_str,'$.key'))
from dataset;

Output: Output:

_col0 _col0
["value1","value2"] [“值 1”,“值 2”]
null null

You can not cast list to string, but if you want you can join list items to string like.您不能将列表转换为字符串,但如果您愿意,可以将列表项加入字符串之类的。

array_join(json_extract(myjson,'$.key'), ' ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM