当使用FOR JSON子句时,如何同时返回包含JSON的文本字段作为JSON结果的一部分?

yeotifhr  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(104)

我的表中的行如下所示:

template_id  template_name  default_job_name  additional_tasks
1            Indiana Courts Hearing           [{"extra_task_id":3,"task_name":"Project Monitoring","task_type":12,"task_notes":"","client_price":null,"ic_cost":null},{"extra_task_id":4,"task_name":"Do Some stuff","task_type":9,"task_notes":"Note","client_price":12,"ic_cost":6}]

我希望以JSON格式返回表:

select template_id, template_name, default_job_name, additional_tasks 
from templates_realtime
FOR JSON PATH

我的JSON如下所示:

[{
    "template_id": 1,
    "template_name": "Indiana Courts",
    "default_job_name": "Hearing",
    "additional_tasks": "[{\"extra_task_id\":3,\"task_name\":\"Project Monitoring\",\"task_type\":12,\"task_notes\":\"\",\"client_price\":null,\"ic_cost\":null},{\"extra_task_id\":4,\"task_name\":\"Do Some stuff\",\"task_type\":9,\"task_notes\":\"Note\",\"client_price\":12,\"ic_cost\":6}]"
}]

如您所见,additional_tasks仍然是一个字符串,我似乎不知道如何将该字段与其他字段一起转换为JSON,我期待得到以下结果:

[{
    "template_id": 1,
    "template_name": "Indiana Courts",
    "default_job_name": "Hearing",
    "additional_tasks": [{
        "extra_task_id": 3,
        "task_name": "Project Monitoring",
        "task_type": 12,
        "task_notes": "",
        "client_price": null,
        "ic_cost": null
    }, {
        "extra_task_id": 4,
        "task_name": "Do Some stuff",
        "task_type": 9,
        "task_notes": "Note",
        "client_price": 12,
        "ic_cost": 6
    }]
}]
wh6knrhe

wh6knrhe1#

使用json_query()将现有JSON嵌入到JSON结果集中,例如:

select
  template_id,
  template_name,
  default_job_name,
  json_query(additional_tasks) as additional_tasks
from templates_realtime
for json path;

其结果为:

[
  {
    "template_id": 1,
    "template_name": "Indiana Courts",
    "default_job_name": "Hearing",
    "additional_tasks": [
      {
        "extra_task_id": 3,
        "task_name": "Project Monitoring",
        "task_type": 12,
        "task_notes": "",
        "client_price": null,
        "ic_cost": null
      },
      {
        "extra_task_id": 4,
        "task_name": "Do Some stuff",
        "task_type": 9,
        "task_notes": "Note",
        "client_price": 12,
        "ic_cost": 6
      }
    ]
  }
]

相关问题