Skip to content

Instantly share code, notes, and snippets.

@oostendo
Created February 3, 2017 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oostendo/b0f4fc3221c457109ada31f74003bee6 to your computer and use it in GitHub Desktop.
Save oostendo/b0f4fc3221c457109ada31f74003bee6 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import ujson as json\n",
"from csv import DictWriter\n",
"\n",
"sslogfile = \"/Users/sm/Code/linedatasimulator/testdata.sslog\"\n",
"staticfields = ['timestamp', 'counter', 'running', 'sslog_type']\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"with open(sslogfile) as sslog:\n",
" lines = [json.loads(line) for line in sslog.readlines()]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"sources = {}\n",
"for line in lines:\n",
" for item in line:\n",
" for v in item.values():\n",
" sources[v['source']] = sources.get(v['source'], {'dynfields': set()})\n",
" sources[v['source']]['dynfields'] = dynamicvals[v['source']]['dynfields'].union(set(v['fieldvalues'].keys()))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for sourcename, source in sources.items():\n",
" source['headerfields'] = sorted(list(source['dynfields']))\n",
" source['csvfile'] = open('testsslog_{}.csv'.format(sourcename), 'w+')\n",
" source['csvwriter'] = DictWriter(source['csvfile'], fieldnames=staticfields + source['headerfields'])\n",
" source['csvwriter'].writeheader()\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"for line in lines:\n",
" for item in line:\n",
" for v in item.values():\n",
" sourcename = v['source']\n",
" source = sources[sourcename]\n",
" \n",
" row = {k: v[k] for k in staticfields}\n",
" row.update({k: v['fieldvalues'].get(k, {}).get('value', None) for k in source['dynfields']})\n",
" \n",
" source['csvwriter'].writerow(row)\n",
" \n",
"for source in sources.values():\n",
" source['csvfile'].close()\n",
" \n",
" \n",
" \n",
"\n",
"\n",
" \n",
" "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment