# DataFrame or DataFrameRow to Dict and JSON

**URL:** <https://discourse.julialang.org/t/dataframe-or-dataframerow-to-dict-and-json/28018>\
**Category:** Data\
**Created:** [August 26, 2019, 11:09pm UTC](https://discourse.julialang.org/t/dataframe-or-dataframerow-to-dict-and-json/28018 "2019-08-26T23:09:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![milesf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/milesf/32/9289_2.png) [@milesf](https://discourse.julialang.org/u/milesf)\
**Post date:** [August 26, 2019, 11:09pm UTC](https://discourse.julialang.org/t/dataframe-or-dataframerow-to-dict-and-json/28018/1 "2019-08-26T23:09:17Z")

</div>

Wanted to double-check if there are any recommended ways to convert a DataFrame (or DataFrameRow) into a Dict (for eventually conversion to JSON). This is the inverse of [this question](https://discourse.julialang.org/t/recommended-way-to-save-and-read-dataframes-in-json-format/8990).

“List of Dicts” JSON format would be ideal.

For example, converting:

```julia
df = DataFrame(x = 1:3, y = 4:6)
3×2 DataFrame
│ Row │ x │ y │
│ │ Int64 │ Int64 │
├─────┼───────┼───────┤
│ 1 │ 1 │ 4 │
│ 2 │ 2 │ 5 │
│ 3 │ 3 │ 6 │

```

to

```julia
[{"x":1,"y":4}
,{"x":2,"y":5}
,{"x":3,"y":6}
]

```

Here’s my basic implementation. Was wondering if there’s anything more efficient out there.

```julia
function dataframe_to_json(df)
    li = []
    for row in eachrow(df)
        di = Dict()
        for name in names(row)
            di[string(name)] = row[name]
        end
        push!(li, di)
    end
    JSON.json(li)
end

df = DataFrame(x = 1:3, y = 4:6)
dataframe_to_json(df)

```

---

<div class="post-metadata">

**Author:** ![jocklawrie](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jocklawrie/32/33616_2.png) [@jocklawrie](https://discourse.julialang.org/u/jocklawrie)\
**Post date:** [August 27, 2019, 6:00am UTC](https://discourse.julialang.org/t/dataframe-or-dataframerow-to-dict-and-json/28018/2 "2019-08-27T06:00:21Z")

</div>

[JSONTables.jl](https://github.com/JuliaData/JSONTables.jl) enables conversion from a Table (or DataFrame) to JSON and back again. However, the recovered table is often not the same as the input table because the package doesn’t preserve types.

[Issue #6](https://github.com/JuliaData/JSONTables.jl/issues/6) in that package concerns this problem and offers a solution, though in its current form the proposed solution is particular to DataFrames (not all types that satisfy the Tables interface) and JSON (not JSON3).

Combining the 2 approaches gives us the best of both worlds - a package that converts between Tables and JSON in either direction without loss of information.
