开发者

replacing a value in a json array with sinatra

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 currentl开发者_开发知识库y 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


if you use the ruby gem "json" you can convert the json string to a hash

require 'json'
converted_hash = JSON(json_string).to_hash

This should be much easier to manage.

You can then turn the hash to a JSON string:

new_json_string = converted_hash.to_json


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.

  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|
      newDoc = doc['value'].dup # <= create a duplicate record and update the value
      newDoc["resources"] = r
      rows.push(newDoc)
    end
  end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜