1

I'm trying to parse multiple json objects in ruby.

def processKey(key)
   obj = getJSONData(key) 
   puts "got log: " + obj.to_s + "\n"
   @data = JSON.parse(obj) 
end

I can see that the obj that I get from getJSONData is correct everytime, however the JSON.parse keeps on returning the first object it parsed

For example:

for key1 -> getJSONData(key1) returns obj1 -> JSON.parse(obj1) returns hash1
for key2 -> getJSONData(key2) returns obj2 -> JSON.parse(obj2) returns hash1
for key3 -> getJSONData(key3) returns obj3 -> JSON.parse(obj3) returns hash1

Why? Looking around at http://www.ruby-doc.org/stdlib-1.9.3/libdoc/json/rdoc/JSON.html and stackoverflow examples I don't notice a way to clean JSON memory or a need to from other exmaples.

What am I doing wrong in regards to JSON.parse? As a note, I'm using ruby on rail 1.9.3 -Thanks, Niru

4

1 回答 1

1

在我的代码中发现了错误。我不小心将数据保留为@data,这是不正确的,因为我做了一些重构。我的方法中的正确代码应该是:

def processKey(key)
   obj = getJSONData(key) 
   data = JSON.parse(obj) 
   return data
end

因为@data 不应该是实例变量,也不应该以这种方式声明。

-谢谢,尼鲁

于 2013-08-23T22:53:24.603 回答