Skip to content

[Bug]: Select "for json" output contains Backslashes when nested #4615

@Teletele-Lin

Description

@Teletele-Lin

What happened?

Select "for json" output contains Backslashes when nested :

-- 1. 创建部门表
CREATE TABLE Departments (
    DeptID INT PRIMARY KEY,
    DeptName NVARCHAR(50),
    Location NVARCHAR(50)
);

-- 2. 创建员工表
CREATE TABLE Employees (
    EmpID INT PRIMARY KEY,
    FullName NVARCHAR(50),
    JobTitle NVARCHAR(50),
    Salary DECIMAL(10, 2),
    DeptID INT, -- 外键
    Email NVARCHAR(100)
);

-- 3. 插入测试数据
INSERT INTO Departments (DeptID, DeptName, Location)
VALUES 
(1, N'研发部', N'北京'),
(2, N'市场部', N'上海');

INSERT INTO Employees (EmpID, FullName, JobTitle, Salary, DeptID, Email)
VALUES 
(101, N'张三', N'高级工程师', 25000.00, 1, 'zhangsan@demo.com'),
(102, N'李四', N'测试工程师', 15000.00, 1, NULL), -- Email 为 NULL
(103, N'王五', N'市场经理', 18000.00, 2, 'wangwu@demo.com');

SELECT 
    d.DeptID,
    d.DeptName,
    -- 子查询:获取该部门下的员工
    (
        SELECT e.FullName, e.JobTitle, e.Email
        FROM Employees e
        WHERE e.DeptID = d.DeptID
        FOR JSON PATH
    ) AS StaffList
FROM Departments d
FOR JSON PATH;

Fix:

CREATE OR REPLACE FUNCTION sys.tsql_select_for_json_result(res sys.NVARCHAR)
RETURNS setof sys.nvarchar_json AS
$$
BEGIN
IF res IS NOT NULL THEN
    return next res;
ELSE
    return;
END IF;
END;
$$
LANGUAGE plpgsql IMMUTABLE;

Version

BABEL_5_X_DEV (Default)

Extension

None

Which flavor of Linux are you using when you see the bug?

No response

Relevant log output

Code of Conduct

  • I agree to follow this project's Code of Conduct.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions