简体   繁体   English

T-SQL - JSON_QUERY:选择属性名称中带有特殊字符的 json 属性

[英]T-SQL - JSON_QUERY : select json properties with special characters in the property name

I'm facing some issues while trying to select a value from a JSON column.我在尝试从 JSON 列中选择值时遇到了一些问题。 The json is: json是:

{
    "$type":"myNameSpace.myClass, myDll"
}

And I'm trying to query it with something like我试图用类似的东西来查询它

SELECT myIdColumnName, myJsonColumnName, JSON_QUERY(myJsonColumnName, '$.$type') as mType

the problem is that the path '$.$type' is invalid, the italian error is:问题是路径 '$.$type' 无效,意大利语错误是:

 Il formato del percorso JSON non è corretto. È stato trovato il carattere imprevisto '$' nella posizione 2.

which basically tells that the parser does not expect "$" after ".".这基本上告诉解析器在“.”之后不期望“$”。 I already tried using '$.type' and '$."$type"' but it in both cases I get null as mType.我已经尝试使用 '$.type' 和 '$."$type"' 但在这两种情况下我都将 mType 设为 null。

Could you tell me the right syntax for this query?你能告诉我这个查询的正确语法吗?

Thank you谢谢

When you want to extract JSON object or scalar value and your path begins with a dollar sign $ , you need to surround it with quotes " . Function JSON_QUERY extracts an object or an array from a JSON string, so JSON_VALUE is more appropriate here when you want to extract a scalar value from JSON text.当您想提取JSON对象或标量值并且您的path以美元符号$开头时,您需要用引号"将其括起来。函数JSON_QUERYJSON字符串中提取一个对象或数组,因此当您使用JSON_VALUE时,这里更合适想要从JSON文本中提取一个标量值。

Example:例子:

DECLARE @json nvarchar(max) = N'{
    "$type":"myNameSpace.myClass, myDll"
}'

SELECT JSON_VALUE(@json, '$."$type"')

Output:输出:

--------------------------
(No column name)
--------------------------
myNameSpace.myClass, myDll

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

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