json 如何添加一个对象到另一个对象,并删除该对象使用震动规格

yeotifhr  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(101)

我想删除所有嵌套数组,并将“location”和“metarecord”的值放在rest json对象中,最后删除这些对象(“location”和“metarecord”)。

{
  "info": [
    {
      "item": "sugar",
      "price": 4,
      "state": "Alberta",
      "country": "Canada"
    },
    {
      "item": "sugar",
      "price": 4.5,
      "state": "California",
      "country": "US"
    }
  ],
  "location": {
    "continent": [
      {
        "country": "US",
        "coordinates": {
          "lang": "97º 00' W",
          "long": "38º 00' N"
        }
      },
      {
        "country": "Canada",
        "coordinates": {
          "lang": "95° 00' W",
          "long": "60° 00' N"
        }
      }
    ]
  },
  "metarecord": {
    "continent": "North America"
  }
}

以下是我想达到的目标:删除所有嵌套数组,并使用国家值将“location”的值放到相应的json对象中(例如,如果一个对象的国家值是“Canada”,那么应该加上location of“canada”),而“metatrecord”是所有对象中的“info”作为其通用属性

[
  {
    "continent": "North America",
    "item": "sugar",
    "price": 4,
    "state": "Alberta",
    "country": "Canada",
    "lang": "95° 00' W",
    "long": "60° 00' N"
  },
  {
    "continent": "North America",
    "item": "sugar",
    "price": 4.5,
    "state": "California",
    "country": "US",
    "lang": "97º 00' W",
    "long": "38º 00' N"
  }
]

我试过的:

[
  {
    "operation": "shift",
    "spec": {
      "info": {
        "*": {
          "item": "[&1].item",
          "price": "[&1].price",
          "state": "[&1].state",
          "country": "[&1].country"
        }
      },
      "location": {
        "continent": {
          "@": "[&1].continent"
        }
      },
      "metarecord": {
        "continent": {
          "*": {
            "$": "[&2].&1"
          }
        }
      }
    }
  }
]

输出:这不是我想要的。

[
  {
    "item": "sugar",
    "price": 4,
    "state": "Alberta",
    "country": "Canada"
  },
  {
    "item": "sugar",
    "price": 4.5,
    "state": "California",
    "country": "US"
  }
]
bmp9r5qi

bmp9r5qi1#

您可以使用以下转换

[
  { // you can group by the countries while matching the ones taken from different arrays
    "operation": "shift",
    "spec": {
      "info": {
        "*": {
          "*": "@1,country.&",
          "@2,location.continent": { // go two levels up the tree to grab the values
            "*": {
              "coordinates": { "*": "@2,country.&" }
            }
          },
          "@2,metarecord.continent": "@1,country.continent"
        }
      }
    }
  },
  { // pick only one from the repeating components for the arrays
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": "ONE"
      }
    }
  },
  { // get rid of the object labels
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]

网站http://jolt-demo.appspot.com/上的演示是:

相关问题