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

查看:137
本文介绍了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""

谢谢.

附言我使用的是 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天全站免登陆