JSON字符串中的插值变量

发布于 2025-01-29 01:31:34 字数 556 浏览 3 评论 0原文

我正在使用下面的代码来创建一个具有变量的函数,该函数可更新JSONB列,或者如果不存在,则可以创建它 - 在这篇文章的帮助

下变量在JSON字符串中$ 2和$ 3。有什么建议吗?

CREATE OR REPLACE FUNCTION public.updateoffset(site text, offsetnumber integer, toscrape integer)
 RETURNS void
 LANGUAGE sql
AS $function$


 update settings set "offset" = coalesce("offset", '{}') || '{"$2": {"toscrape":3$}}'
  where site = $1;
$function$ 

I am using the code below to create a function with variables that updates a jsonb column with a json object or create it if it doesn't exist - With help from this post

However I am really having trouble interpolating the variables $2 and $3 in the json string. Any suggestions?

CREATE OR REPLACE FUNCTION public.updateoffset(site text, offsetnumber integer, toscrape integer)
 RETURNS void
 LANGUAGE sql
AS $function$


 update settings set "offset" = coalesce("offset", '{}') || '{"$2": {"toscrape":3$}}'
  where site = $1;
$function$ 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放肆 2025-02-05 01:31:34

请勿使用字符串插值来构建JSON值 - 使用相反,特别是json_build_object

update settings
set "offset" = coalesce("offset", '{}') || json_build_object($2, json_build_object('toscrape', $3))
where site = $1;

也可能更简单地使用json_set :(

update settings
set "offset" = json_set(coalesce("offset", '{}'), ARRAY[$2::text,'toscrape'], $3)
where site = $1;

但是,它确实将其他属性保留在内在对象中,而不是将其完全替换为对象只有toscrape作为密钥)

Do not use string interpolation for building JSON values - use JSON functions and operators instead, particularly json_build_object:

update settings
set "offset" = coalesce("offset", '{}') || json_build_object($2, json_build_object('toscrape', $3))
where site = $1;

Also it might be simpler to use json_set:

update settings
set "offset" = json_set(coalesce("offset", '{}'), ARRAY[$2::text,'toscrape'], $3)
where site = $1;

(which, however, does keep other properties in the inner object, not replacing it completely with an object that has only toscrape as a key)

执笏见 2025-02-05 01:31:34

使用函数

...
  update settings
  set "offset" = 
    coalesce("offset", '{}') || format('{"%s": {"toscrape":%s}}', $2, $3)::jsonb
  where site = $1;
...

Use the function format().

...
  update settings
  set "offset" = 
    coalesce("offset", '{}') || format('{"%s": {"toscrape":%s}}', $2, $3)::jsonb
  where site = $1;
...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文