繁体   English   中英

将Field字符串Json转换成C#或SQL中的Parse Format

[英]Convert Field string Json to Parse Format in c# or SQL

这是一种保存在数据库中的多语言数据格式,我正在使用 dapper 来获取名称。下面是获取时的输出。

"firstName":"{
    \"ar-AE\": \مستم"\",
    \"en-US\": \"test\"
}"

我需要在下面提到的解析格式(预期输出)

"firstName":{"ar-AE": "مستم","en-US":"test"}

这是 DTO 类

DTO.cs

class DTO
{
    public string FirstName
}

从 dapper 获取时,它返回列表。 所以从响应列表我可以这样做

list.select(x=> JSON.Deserialize<string>(x.firstName)) 

我如何更改现有列表以解析 JSON,以便获得预期的输出

SQL:我正在使用的简单选择查询也或者对 SQL 的建议

select FirstName from TableA

CSharp 或 SQL 有什么建议吗?

我需要这样的输出从列表中返回

在此处输入图像描述

我尝试转换第一个字符串,但无法将其识别为 JSON 字符串。 然后我尝试相反,使用 string_escape( <json string> , 'json') 并得到一个与你的不同的字符串。

这篇文章中的第一个字符串是否有可能格式错误? 双引号围绕مستم似乎放错了地方。 当我将位置从\مستم"\"更改为\"مستم\"时,我得到了一个有效的 json 对象。 我希望它与从右到左阅读有关,并且双引号移到了值的开头。

要验证的 T-SQL 代码

declare @json nvarchar(max) = N'"firstName":"{    \"ar-AE\": \"مستم\",    \"en-US\": \"test\"  }"';
declare @path nVARCHAR(max);

print 'isJSON( '''+@json+''')  --> '+case isJSON(@json) when 0 then 'false' when 1 then 'true' else 'unknown' end;
print 'add missing {} '
set @json = case when isJSON(@json) = 0 then N'{'+@json+N'}' else @json end;
print 'isJSON('''+@json+''') --> '+case isJSON(@json) when 0 then 'false' when 1 then 'true' else 'unknown' end;

set @path=N'$';
select @json                        as [@json]
     , @path                        as [@path]
     , json_query(@json, @path)     as [json_query]
     , json_value(@json, @path)     as [json_value]

set @path=N'$.firstName';
select @json                        as [@json]
     , @path                        as [@path]
     , json_query(@json, @path)     as [json_query]
     , json_value(@json, @path)     as [json_value]

并反转

declare @json nvarchar(max);
-- now paste the expected result in a variable
set @json = N'"firstName":{"ar-AE": "مستم","en-US":"test"}'

-- test if the string is a valid JSON object
select isJSON(@json) as [original is JSON?]
     , isJSON(N'{'+@json+N'}') as [modified is JSON?]

-- the surrounding {} are missing, adding them now
set @json = N'{'+@json+N'}'

-- ways to query the JSON object
select * from openJSON(@json);
select JSON_QUERY(@json, N'$') as [JSON-query];

select string_escape(@json, 'json') as [expected input]

暂无
暂无

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

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