Hi JobJob, I like that too. Thanks!
When I got my df2json working, the next thing I naturally did was try JSON.parse(json) and saw I got back an array of Dicts, so thought constructing an array of Dicts from a DataFrame could also be a way to go, but couldn't get it to work. Your solution nicely solves that problem :) It also gives a good clue how to go the other way. I'll also need to go from an array of Dicts (parsed from the above) to a DataFrame. Thanks both. This is a good learning experience I'll share with my team. On Tuesday, November 10, 2015 at 2:19:48 AM UTC+8, JobJob wrote: > > It doesn't pretty print, but is there anything wrong with this: > > using JSON > json([[string(col)=> df[col][row] for col in names(df)] for row in > 1:nrow(df)]) > > Just to break it down, this part creates the dictionary for each row: > > [string(col)=> df[col][row] for col in names(df)] > > and it's repeated over each row to create the array of Dicts. > > and of course json() converts the array of dicts to valid json (which is > not that hard to get wrong when done by hand). > > On Monday, 9 November 2015 06:11:17 UTC+2, Eric Forgy wrote: >> >> Hi, >> >> I need to serialize a DataFrame to JSON. I have read this: >> >> - https://github.com/JuliaStats/DataFrames.jl/issues/184 >> >> but my case is a little different. >> >> If my DataFrame looks like this: >> >> julia> df >> 8x2 DataFrames.DataFrame >> | Row | A | B | >> |-----|---|-----| >> | 1 | 1 | "M" | >> | 2 | 2 | "F" | >> | 3 | 3 | "F" | >> | 4 | 4 | "M" | >> | 5 | 5 | "F" | >> | 6 | 6 | "M" | >> | 7 | 7 | "M" | >> | 8 | 8 | "F" | >> >> >> Then I need my JSON to look like this (in order to talk to another API): >> >> [ >> >> {"A": 1, "B": "M"}, >> >> {"A": 2, "B": "F"}, >> >> {"A": 3, "B": "F"}, >> >> {"A": 4, "B": "M"}, >> >> {"A": 5, "B": "F"}, >> >> {"A": 6, "B": "M"}, >> >> {"A": 7, "B": "M"}, >> >> {"A": 8, "B": "F"}, >> >> ] >> >> >> In Matlab, I would create an array of "structs". In Julia, I'm thinking I >> would need to dynamically create a type >> >> immutable row >> A::Int >> B::AbstractString >> end >> >> >> based on the names in the DataFrame, which should be generic and not >> confined to two. Then I would construct an array of "row"s and finally >> using JSON.jl, serialize via JSON.json. >> >> Is there a better/easier way to do this? >> >> Thank you. >> >
