python - 使用其他嵌入的 JSON 对象展平 JSON 对象

标签 python ruby json

我有一个 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/

相关文章:

javascript - javascript 的第二位,用于更改前一个 javascript block 中的设置

python - 使用python,是否可以直接将表单数据发送到网站服务器并在不使用浏览器的情况下接收响应?

python - 使用 python pandas 将 json 转换为 csv

ruby - 我如何使用 savon 嵌套数组属性!哈希?

ruby - 如何使用 Ruby 中的特定步骤迭代反向范围?

python - 从请求中获取 JSON 参数,我得到 : 'method' object is not subscriptable

python - 如何获取Python字典最高值的键

python - 使用 SQLAlchemy Core 选择多行中的第一行

ruby-on-rails - 事件资​​源嵌套路由

php - 在php中插入计算代码后出错