Postgres:如何将 json 字符串转换为文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27215216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:39:30  来源:igfitidea点击:

Postgres: How to convert a json string to text?

jsonpostgresql

提问by e79ene

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

Json 值可能由字符串值组成。例如。:

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

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

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

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

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

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

Thanks.

谢谢。

P.S. I'm using PostgreSQL 9.3

PS 我使用的是 PostgreSQL 9.3

采纳答案by Robert M. Lefkowitz

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

在 PostgreSQL 中没有办法解构一个标量 JSON 对象。因此,正如你所指出的,

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

is 15,

是 15,

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

诀窍是将 JSON 转换为一个包含一个 JSON 元素的数组,然后使用->>.

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

will return 11.

将返回 11。

回答by Ian Timothy

In 9.4.4 using the #>>operator works for me:

在 9.4.4 中使用#>>操作符对我有用:

select to_json('test'::text) #>> '{}';

To use with a table column:

与表列一起使用:

select jsoncol #>> '{}' from mytable;

回答by Mr. Curious

Mr. Curious was curious about this as well. In addition to the #>> '{}'operator, in 9.6+ one can get the value of a jsonb string with the ->>operator:

好奇先生对此也很好奇。除了#>> '{}'运算符,在 9.6+ 中还可以通过运算符获取 jsonb 字符串的值->>

select to_jsonb('Some "text"'::TEXT)->>0;
  ?column?
-------------
 Some "text"
(1 row)

If one has a json value, then the solution is to cast into jsonb first:

如果有一个 json 值,那么解决方案是先转换成 jsonb:

select to_json('Some "text"'::TEXT)::jsonb->>0;
  ?column?
-------------
 Some "text"
(1 row)

回答by Zhemin Zhou

An easy way of doing this:

一个简单的方法来做到这一点:

SELECT  ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;

Just convert the json string into a json list

只需将 json 字符串转换为 json 列表