用 sinatra 替换 json 数组中的值
我有带有“资源”字段的记录,其中可以包含多个资源。当我返回此数据时,我需要迭代该字段并为该字段中的每个值返回一条单独的记录。我目前正在使用 sinatra 并且能够对字段进行交互,但是我很难替换 json 数组中的字段。
例如 事件: 名称 资源:resourceA、resourceB、resourceC
该记录需要作为 3 个唯一记录/事件返回,每个记录只有一个资源。
使用下面列出的代码,我得到了三个记录,但是所有三个记录都以相同的资源值(resourceC)返回,
这是我的代码,
docs = @db.view('lab/events', :startkey => params[:startDate], :endkey => endSearch)['rows']
rows = Array.new
docs.each do |doc|
resources = doc['value']['resources'].split(",")
resources.each do |r|
doc['value']['resources'] = r
rows.push(doc['value'])
end
end
非常感谢任何帮助。 谢谢 克里斯
I have records with a 'resource' field which can contain multiple resources. When I return this data, I need to iterate over this field and return an individual record for each value in the field. I am currently using sinatra and am able to interate over the fields okay, but I am having difficulty replacing the field in the json array.
For example
event: Name
resources: resourceA, resourceB, resourceC
This record needs to be returned as 3 uniqe records/events with only one resource per record.
With the code listed below, I am getting three records, but all three records are coming back with the same resource value (resourceC)
Here is my code
docs = @db.view('lab/events', :startkey => params[:startDate], :endkey => endSearch)['rows']
rows = Array.new
docs.each do |doc|
resources = doc['value']['resources'].split(",")
resources.each do |r|
doc['value']['resources'] = r
rows.push(doc['value'])
end
end
Any help is greatly appreciated.
Thanks
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用 ruby gem“json”,您可以将 json 字符串转换为哈希值,
这应该更容易管理。
然后您可以将哈希值转换为 JSON 字符串:
if you use the ruby gem "json" you can convert the json string to a hash
This should be much easier to manage.
You can then turn the hash to a JSON string:
基本上发生的事情是 ruby 将所有三个记录视为同一个记录,因此当一个记录上的哈希值更新时,它会影响从同一文档创建的所有其他记录。为了解决这个问题,我实际上需要每次都创建一个重复的记录并修改它的值。
Basically what is happening is ruby is seeing all three records as the same record so as the hash value is updated on one record, it impacts all other records that were created from the same doc. To get around this, I acutally needed to create a duplicate record each time through and modify it's value.