我有以下JSON文件:
{
title: "Children's Magazine",
labels: [
{
category: 1
edition: "first"
}
],
release: "11/22/1982"
title: "Some book",
labels: [
{
category: 1
edition: "first"
}
]
release: "11/22/1982"
}
如何在不包含category
的情况下将其转换为 Ruby数组,因此数组看起来像这样:
[
title: "Children's Magazine",
labels: [
{
edition: "first"
}
],
release: "11/22/1982"
title: "Some book",
labels: [
{
edition: "first"
}
]
release: "11/22/1982"
]
我在使用这些嵌套的JSON转换到Ruby数组时遇到了麻烦......提前感谢!
答案 0 :(得分:0)
我认为这是您正在处理的JSON结构:
[
{
"title": "Children's Magazine",
"labels": [
{
"category": 1,
"edition": "first"
}
],
"release": "11/22/1982"
},
{
"title": "Some book",
"labels": [
{
"category": 1,
"edition": "first"
}
]
"release": "11/22/1982"
}
]
在这种情况下,您可以require 'json'
使用Ruby JSON library。这将为您提供所需的Ruby数组。
要删除"category"
元素,您可以在JSON::parse
的数组上使用Array#each
并删除"category"
元素。最终的代码可能看起来像这样
require 'json'
array = JSON.parse(json_string)
array.each { |book| book['labels'].delete('category') }