Postgres:如何将json字符串转换为文本? [英] Postgres: How to convert a json string to text?

查看:1815
本文介绍了Postgres:如何将json字符串转换为文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Json值可以由字符串值组成.例如:

Json value may consist of a string value. eg.:

postgres=# SELECT to_json('Some "text"'::TEXT);
     to_json
-----------------
 "Some \"text\""

如何提取该字符串作为postgres文本值?

How can I extract that string as a postgres text value?

::TEXT不起作用.它返回带引号的json,而不是原始字符串:

::TEXT doesn't work. It returns quoted json, not the original string:

postgres=# SELECT to_json('Some "text"'::TEXT)::TEXT;
     to_json
-----------------
 "Some \"text\""

谢谢.

P.S.我正在使用PostgreSQL 9.3

P.S. I'm using PostgreSQL 9.3

推荐答案

PostgreSQL中没有办法解构标量JSON对象.因此,正如您所指出的那样,

There is no way in PostgreSQL to deconstruct a scalar JSON object. Thus, as you point out,

select  length(to_json('Some "text"'::TEXT) ::TEXT);

是15

技巧是将JSON转换为一个JSON元素的数组,然后使用->>提取该元素.

The trick is to convert the JSON into an array of one JSON element, then extract that element using ->>.

select length( array_to_json(array[to_json('Some "text"'::TEXT)])->>0 );

将返回11.

这篇关于Postgres:如何将json字符串转换为文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆