Bitcoin Forum

Bitcoin => Development & Technical Discussion => Topic started by: mikegogulski on June 08, 2011, 04:49:26 PM



Title: json-to-csv.py: a handy tool for wallet transaction analysis
Post by: mikegogulski on June 08, 2011, 04:49:26 PM
I'm sure somebody has rolled this up before, but I had cause to today.

Usage:
 bitcoind listtransactions '*' 999999 | python json-to-csv.py > transactions.csv
 Use favorite spreadsheet program to open transactions.csv

Code:
#!/usr/bin/python

import json
import sys

input = sys.stdin.read()
data = json.loads(input)

keys = []

for record in data:
for key in record:
if key not in keys:
keys.append(key)

cur = ""
output = ""

for key in keys:
output += '"' + key + '",'
output += '\n'

for record in data:
for key in keys:
if key in record:
if record[key].__class__ is int or record[key].__class__ is float:
output += str(record[key])
else:
output += '"' + record[key] + '"'
output += ','
output += '\n'

print output


Title: Re: json-to-csv.py: a handy tool for wallet transaction analysis
Post by: Gavin Andresen on June 08, 2011, 11:46:56 PM
I think I meant to post my version and just got busy and forgot...
Quote
#!/usr/bin/env python
#
# Reads an array of JSON objects and writes out CSV-format,
# with key names in first row.
# Columns will be union of all keys in the objects.
#

import csv
import json
import sys

json_string = sys.stdin.read()
json_array = json.loads(json_string)

columns = set()
for item in json_array:
  columns.update(set(item))

writer = csv.writer(sys.stdout)
writer.writerow(list(columns))
for item in json_array:
  row = []
  for c in columns:
    if c in item: row.append(str(item[c]))
    else: row.append('')
  writer.writerow(row)


Title: Re: json-to-csv.py: a handy tool for wallet transaction analysis
Post by: mikegogulski on June 09, 2011, 12:59:57 AM
I think I meant to post my version and just got busy and forgot...

Oh. There's a python CSV module. *facepalm*. Way sexier, sir!