PostgreSQL JSON查询返回NULL

时间:2018-08-15 22:39:36

标签: json postgresql unity3d

我已经使用Unity提供的JSON文件将原始数据从Unity导出到PostgreSQL中。

数据样本:

{"name":"EVENT1","ts":1534117312648,"userid":"1e77723b38980460ea307db5fca875fd","sessionid":"3188654687037448331","platform":"AndroidPlayer","sdk_ver":"u2017.4.1f1","debug_device":false,"user_agent":"Dalvik/2.1.0 (Linux; U; Android 7.0; LG-H820 Build/NRD90U)","submit_time":1534118874283,"custom_params":{"the Daily Bonus":"RewardGems"},"country":"US","city":"Fayetteville","appid":"50d97d88-096c-4a4b-8daa-390e239974f8","type":"custom"}
{"name":"GAME1","ts":1534107814910,"userid":"f029c3982539e4eeea171132bd9cf8c9","sessionid":"220388644753439310","platform":"AndroidPlayer","sdk_ver":"u2017.4.1f1","debug_device":false,"user_agent":"Dalvik/2.1.0 (Linux; U; Android 7.0; SM-G570M Build/NRD90M)","submit_time":1534118931705,"custom_params":{"Heavy Slam":"1","Flame Breath":"1","Cure":"1","Chop":"1","Bite":"7","Fang Fireball":"10","Axe Throw":"2"},"country":"BR","city":"Várzea Grande","appid":"50d97d88-096c-4a4b-8daa-390e239974f8","type":"custom"} 

JSON数据作为文本数据类型位于values表的temp_json列中。尝试将列作为JSON数据类型CAST时,出现以下错误:

ERROR:  invalid input syntax for type json
DETAIL:  Character with value 0x0a must be escaped.
CONTEXT:  JSON data, line 1: ...tric Jacket":"1","Bolt":"5","Axe Throw":"1","Toss
SQL state: 22P02

结果,我不得不使用to_json(values)将text列转换为JSON。当我尝试运行以下查询时:

SELECT to_json(values) -> 'name'
FROM temp_json

我的查询结果为NULL。我四处搜寻,找到了一个答案,可以尝试以下查询:

select json_array_elements(to_json(values)) ->> 'name'
from temp_json

尽管会导致以下错误:

ERROR:  cannot call json_array_elements on a scalar
SQL state: 22023

我对JSON和PostgreSQL非常陌生,因此为noob问题表示歉意。任何帮助将不胜感激。我觉得这应该很容易解决,但是我似乎找不到解决方案。

1 个答案:

答案 0 :(得分:0)

如果您尝试从JSON字符串返回“名称”参数,则可以使用JSON_EXTRACT_PATH_TEXT函数。查看文件: https://docs.aws.amazon.com/redshift/latest/dg/JSON_EXTRACT_PATH_TEXT.html

下面是一个示例,假设JSON字符串位于temp_json表的values列中,

SELECT JSON_EXTRACT_PATH_TEXT(values, 'name') AS name
FROM temp_json;

希望这会有所帮助!