简体   繁体   English

带有JSON变量的JSON对象

[英]JSON Object with variables into PostgreSQL

I have the following function: 我有以下功能:

create or replace function something(id integer)
  RETURNS INTEGER
language plpgsql
as $$
  DECLARE
  name varchar;
  email varchar;
  route varchar;
  now timestamp;
  BEGIN
    now = current_timestamp;
    SELECT apd.apd_nome, apd.apd_email, CAST(r.rota_params->>'url_completa' as varchar) into name, email, route FROM avise_produto_disponivel apd
      inner join produto p on apd.pro_id = p.pro_id
      inner join produto_div div on p.pro_id = div.pro_id
      inner join produto_oferta_div pod on div.pod_id = pod.pod_id
      inner join produto_oferta po on po.ofe_id = pod.ofe_id
      inner join rotas r on CAST(r.rota_params->>'oferta_id' as integer) = po.ofe_id
    where apd.pro_id = $1;
    DELETE FROM avise_produto_disponivel where pro_id = $1;
    rota = CONCAT('https://www.something.com/', route);
    INSERT INTO comunicacao (cot_id, com_para, com_assunto, com_data_criado, com_parametros, com_para_nome, cos_id, com_de) VALUES (1, email, 'Produto Chegou', now, '{"NOME": name, "URL": route}', name, 1, 'correio');
    return 1;
  END;
$$ ;

But when I try to execute I get the following error: 但是当我尝试执行时,出现以下错误:

[22P02] ERROR: invalid input syntax for type json Detalhe: Token "nome" is invalid. Where: JSON data, line 1: {"NOME": name... PL/pgSQL function avise_me(integer) line 18 at SQL statement

Thanks in advance. 提前致谢。

you can test the usage of the JSON syntax by castin, test 您可以通过castin测试JSON语法的使用情况,测试

   SELECT '{"NOME": "JOÃO", "URL": "http://rota.com.br"}'::json;

It is a string representation transformed into JSON... And is not what you need. 它是一个转换为JSON的字符串表示形式...并不是您所需要的。 Try to use at INSERT INTO comunicacao something as 尝试在INSERT INTO comunicacao使用以下内容

  json_build_object('nome', name,  'URL', route)

See https://www.postgresql.org/docs/current/functions-json.html 参见https://www.postgresql.org/docs/current/functions-json.html


PS1: seems that there are also an error at the initial "SELECT INTO". PS1:似乎在初始“ SELECT INTO”处也存在错误。

PS2: I preefer to use JSONb instead JSON in near all application. PS2:我更喜欢在几乎所有应用程序中使用JSONb而不是JSON。

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

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