Skip to content
Snippets Groups Projects
Commit 5a6ee0c8 authored by rswindell's avatar rswindell
Browse files

So I was playing with serialized JSON data files (a replacement for the old

logon.lst file format) and thought I came up with a cool new idea. Nope.
It's already a thing:
http://jsonlines.org/
http://ndjson.org/

Here's a library to append-to and read these "JSON Lines", "NDJSON" and
"LDJSON" files.

On underscores versus dashes in filenames:
Apparently my tendency is to use underscores in source/script filenames, while
other CVS contributors (e.g. mcmlxxix) prefer dashes (e.g. json-*.js), so the
filenames are starting to look a bit bipolar. Oh well. :-(
parent ebd19f29
No related branches found
No related tags found
No related merge requests found
// $Id$
// Library for dealing with "JSON Lines" (.jsonl)
// and "Newline Delimited JSON" (.ndjson) files
"use strict";
// Return true (success) or a string with an error
function add(filename, obj)
{
var f = new File(filename);
if(!f.open("a")) {
return "Error " + f.error + " opening " + filename;
}
f.writeln(JSON.stringify(obj));
f.close();
return true;
}
// Returns an array object on success, string on error
// Pass a positive 'num' to return first num objects from file
// Pass a negative 'num' to return last -num objects from file
// If max_line_len == 0, default is 4096
// Pass 'recover' value of true to ignore unparseable lines
function get(filename, num, max_line_len, recover)
{
var f = new File(filename);
if(!f.open("r", true)) {
return "Error " + f.error + " opening " + filename;
}
if(!max_line_len)
max_line_len = 4096;
var lines = f.readAll(max_line_len);
f.close();
if(num > 0)
lines = lines.slice(0, num);
else if(num < 0)
lines = lines.slice(num);
var list = [];
for(var i in lines) {
try {
var obj = JSON.parse(lines[i]);
list.push(obj);
} catch(e) {
if(!recover)
return e + " line " + (Number(i) + 1) + " of " + filename;
}
}
return list;
}
this;
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment