我在Julia中有一个数据帧,如df = DataFrame(A = 1:4,B = [“M”,“F”,“F”,“M”])。我必须将它转换为像
这样的JSON{
"nodes": [
{
"A": "1",
"B": "M"
},
{
"A": "2",
"B": "F"
},
{
"A": "3",
"B": "F"
},
{
"A": "4",
"B": "M"
}
]
}
请帮助我。
答案 0 :(得分:3)
DataFrames中没有一种方法可以做到这一点。在github issue中,使用JSON.jl的以下代码段作为写入json的方法提供:
using JSON
using DataFrames
function df2json(df::DataFrame)
len = length(df[:,1])
indices = names(df)
jsonarray = [Dict([string(index) => (isna(df[index][i])? nothing : df[index][i])
for index in indices])
for i in 1:len]
return JSON.json(jsonarray)
end
function writejson(path::String,df::DataFrame)
open(path,"w") do f
write(f,df2json(df))
end
end