【问题标题】:JSONPath expressions: getting the value of a specific attribute based on it's presence or the value of another attributeJSONPath 表达式:根据特定属性的存在或另一个属性的值获取特定属性的值
【发布时间】:2015-06-16 03:17:57
【问题描述】:

我的 JSON 结构是一种嵌套的父/子结构:

{
  "type": "site",
  "profile_id": "site profile id",
  "children": [
    {
      "type": "dealer",
      "profile_id": "dealer profile id",
      "children": [
        {
          "type": "location",
          "profile_id": "location profile id",
          "children": [
            {
              "type": "customer",
              "profile_id": "customer profile id",
              "children": [
                {
                  "type": "farm",
                  "farm_id": "farm id",
                  "children": [
                    {
                      "type": "field",
                      "field_id": "field id"
                     }]}]}]}]}]}

JSONPath 中是否有某种方法可以执行以下操作之一:

  1. 如果有 profile_id,请给我,如果有,请给我 farm_id 它存在,或者如果存在,请给我 field_id。

  2. 如果 type=customer,给我 profile_id,如果 type=farm,给我 farm_id,如果 type=field,给我 field_id

  3. 给我每个类的第 n 个属性。 id 实际上是每个类中的第三个属性。这是我最不喜欢的选项,因为我不知道 id 是否永远是第三个属性。

【问题讨论】:

  • 如果你愿意做三个 JSONPath 调用,选项 2 会很简单。例如,如果 type=customer 则获取 profile_id 如下所示:$..[?(@.type=='customer')].profile_id。另一个例子见link。此外,由于您可能会遇到此问题,因此您的 JSON 中缺少一些语法,例如字段之间的逗号,以及属性名称周围的双引号。
  • 邓肯,这很适合我的情况。还要感谢您指出语法。我将编辑问题以改进它。
  • 很高兴我能帮上忙。然后我会将其作为官方答案提交,以便关闭问题。

标签: json jsonpath


【解决方案1】:

需要 3 个单独查询的选项 2 的解决方案如下。以下是 3 个查询:

$..[?(@.type=='customer')].profile_id
$..[?(@.type=='farm')].farm_id
$..[?(@.type=='field')].field_id

我用http://www.jsonquerytool.com验证了这些查询

有关类似示例,另请参阅 this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多