我有一个 JSON 对象,如下所示:
{ "name":"bacon" "category":["food","meat","good"] "calories":"huge" }
I am trying to flatten that into an array of unique values. I need to build a fact table for Tableau which is not able to work with cross-tabulated data or JSON data directly.
I am not picky about whether I do this in Python or Ruby, but so far I've been trying to do it in Ruby. I am able to easily parse the JSON and get a Ruby hash out of it which seems like the right thing to do first.
{"name"=>"bacon", "category"=>["food", "meat", "good"], "calories" => "huge"}
and I need to produce this:
name,category,calories
bacon,food,huge
bacon,meat,huge
bacon,good,huge
所以我认为我需要循环该哈希并尝试取消嵌套它。我一直在尝试这样的事情:
def Flatten(inHash)
inHash.each do |key,value|
if value.kind_of?(Hash)
Flatten(value)
else
puts "#{value}"
end
end
end
但是,这似乎打印了所有值,但它不会重复之前的值。所以我得到的输出看起来像
bacon
food
meat
good
huge
是否有内置的方法、gem 或库可以实现这个或我正在从头开始构建?关于如何获得我想要的输出有什么想法吗?我会说 Ruby 和 Python,所以如果您有 Python 答案,请分享。
最佳答案
>>> #Assuming your json data is correctly formatted as is as follows
>>> data = '{ "name":"bacon", "category":["food","meat","good"], "calories":"huge" }'
>>> #Lets call our json parser as foo (I am bad with names)
>>> def foo(data):
#You first need to parse it to a Py Object
json_data = json.loads(data)
from collections import namedtuple
#Now create a namedtuple with the given keys of the dictionary
food_matrix = namedtuple('food_matrix',json_data.keys())
#And create a tuple out of the values
data_tuple = food_matrix(*json_data.values())
#Now with itertools.product create a cross product
from itertools import product
data_matrix = list(product([data_tuple.name],data_tuple.category, [data_tuple.calories]))
# Now display the heading
print "{:15}{:15}{:15}".format(["name","category","calories")
# Now display the values
for e in data_matrix:
print "{:15}{:15}{:15}".format(*e)
>>> #Now call it
>>> foo(data)
name category calories
bacon food huge
bacon meat huge
bacon good huge
>>>
关于python - 使用其他嵌入的 JSON 对象展平 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15251061/