简体   繁体   English

当多个节点共享相同的名称时,使用 Oracle SQL 获取 JSON_VALUE

[英]Get JSON_VALUE with Oracle SQL when multiple nodes share the same name

I have an issue where I have some JSON stored in my oracle database, and I need to extract values from it.我有一个问题,我的 oracle 数据库中存储了一些 JSON,我需要从中提取值。

The problem is, there are some fields that are duplicated.问题是,有些字段是重复的。

When I try this, it works as there is only one firstname key in the options array:当我尝试这个时,它可以工作,因为 options 数组中只有一个 firstname 键:

    SELECT 
    JSON_VALUE('{"increment_id":"2500000043","item_id":"845768","options":[{"firstname":"Kevin"},{"lastname":"Test"}]}', '$.options.firstname') AS value
   FROM DUAL;

Which returns 'Kevin'.返回“凯文”。

However, when there are two values for the firstname field:但是,当 firstname 字段有两个值时:

SELECT JSON_VALUE('{"increment_id":"2500000043","item_id":"845768","options":[{"firstname":"Kevin"},{"firstname":"Okay"},{"lastname":"Test"}]}', '$.options.firstname') AS value
  FROM DUAL;

It only returns NULL.它只返回NULL。

Is there any way to select the first occurence of 'firstname' in this context?在这种情况下,有没有办法选择“firstname”的第一次出现?

JSON_VALUE returns one SQL VALUE from the JSON data (or SQL NULL if the key does not exists). JSON_VALUE 从 JSON 数据返回一个 SQL VALUE(如果键不存在,则返回 SQL NULL)。

If you have a collection of values (a JSON array) an you want one specific item of the array you use array subscripts (square brackets) like in JavaScript, for example [2] to select the third item.如果您有一组值(一个 JSON 数组),并且您想要数组中的一个特定项,那么您可以像在 JavaScript 中一样使用数组下标(方括号),例如 [2] 来选择第三项。 [0] selects the first item. [0] 选择第一项。 To get the first array item in your example you have to change the path expression from '$.options.firstname' to '$.options[0].firstname'要获得示例中的第一个数组项,您必须将路径表达式从 '$.options.firstname' 更改为 '$.options[0].firstname'

You can follow this query:-您可以按照此查询:-

SELECT JSON_VALUE('{
  "increment_id": "2500000043",
  "item_id": "845768",
  "options": [
    {
      "firstname": "Kevin"
    },
    {
      "firstname": "Okay"
    },
    {
      "lastname": "Test"
    }
  ]
}', '$.options[0].firstname') AS value
  FROM DUAL;

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

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