Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ODS file to JSON

I would like to convert my speadsheet of data to a JSON array of array.

This site do it: http://www.shancarter.com/data_converter/index.html And I looked into the source code.

But what I would like is a macro / script / extension or any way to programm it to convert my .ods into a JSON file:

Like:

NAME    VALUE   COLOR   DATE
Alan    12  blue    Sep. 25, 2009
Shan    13  "green  blue"   Sep. 27, 2009
John    45  orange  Sep. 29, 2009
Minna   27  teal    Sep. 30, 2009

To:

[
    ["Alan",12,"blue","Sep. 25, 2009"],
    ["Shan",13,"green\tblue","Sep. 27, 2009"],
    ["John",45,"orange","Sep. 29, 2009"],
    ["Minna",27,"teal","Sep. 30, 2009"]
]
like image 339
damio Avatar asked Feb 19 '12 21:02

damio


2 Answers

The answer might be again late but marcoconti83 has done exactly that: reading a ods file and return them as two dimensional arrays.

https://github.com/marcoconti83/read-ods-with-odfpy/blob/master/ODSReader.py

Once you have the data in arrays, it's not that difficult to get them into a json file. Here's example code:

import json
from odftoarray import ODSReader  # renamed the file to odftoarray.py

r = ODSReader("your_file.ods")
arrays = r.getSheet("your_data_sheet_name")
json.dumps(arrays)
like image 169
chfw Avatar answered Oct 04 '22 06:10

chfw


This may be a bit late but for those who come looking and want to do this it would likely be best to save the .ods file as .csv which nearly all spreadsheet programs can do. Then use something like this to convert it:

import csv
import sys
import json, os


def convert(csv_filename, fieldnames):
    print ("Opening CSV file: ",csv_filename)
    f=open(csv_filename, 'r')
    csv_reader = csv.DictReader(f,fieldnames)
    json_filename = csv_filename.split(".")[0]+".json"

    print ("Saving JSON to file: ",json_filename)
    jsonf = open(json_filename,'w') 
    data = json.dumps([r for r in csv_reader])
    jsonf.write(data) 
    f.close()
    jsonf.close()


csvfile = ('path/to/the/csv/file.csv')
field_names = [
                "a",
                "list",
                "of",
                "fieldnames"
            ]

convert(csvfile, field_names)

And a tip, csv is pretty human readable so just go through and make sure it saved in the format you want and then run this script to convert it to JSON. Check it out in a JSON viewer like JSONView and then you should be good to go!

like image 22
clifgray Avatar answered Oct 04 '22 07:10

clifgray