You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中是否存在支持嵌套JSON字段筛选与格式化的Gem?

推荐的Ruby Gem:jmespath-ruby

你需要的功能可以通过 jmespath-ruby 实现,它支持用类似点分隔的路径语法提取嵌套JSON(包括数组、嵌套数组)中的指定字段,还能自动处理数组元素的扁平化合并,最终生成一级嵌套的JSON结构。

具体用法示例

  1. 先安装Gem:
gem install jmespath
  1. 对应你的需求编写代码:
require 'jmespath'
require 'json'

# 原JSON数据
original_json = <<~JSON
[{
  "key1": "test",
  "key2": "Test",
  "key3": "Test",
  "key4": [
    {"key1": "test"}
  ],
  "key5": {
    "key6": "test",
    "key7": [
      {"key8": ["test", "test"]},
      {"key8": ["test2", "test3"]}
    ]
  }
}]
JSON

# 解析原JSON为Ruby对象
data = JSON.parse(original_json)

# 构造JMESPath表达式,匹配你需要的字段
expression = '[].{key1: key1, key2: key2, key8: key5.key7[*].key8[]}'

# 执行提取
result = JMESPath.search(expression, data)

# 输出格式化后的结果
puts JSON.pretty_generate(result)

输出结果

[
  {
    "key1": "test",
    "key2": "Test",
    "key8": [
      "test",
      "test",
      "test2",
      "test3"
    ]
  }
]

语法说明

  • [].{...}:遍历原数组中的每个对象,构造新的结构
  • key5.key7[*].key8[]:key7[*]遍历key7数组的所有元素,key8[]将每个key8的数组元素扁平化,最终合并成一个一维数组

内容的提问来源于stack exchange,提问作者john bowlee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 06:05:36