It's native and full javascript implementation of JSONWriter class. The API is complete and flexible. JSON is still valid.
With npm do:
$ npm install json-writer
var JSONWriter = require('json-writer');
jw = new JSONWriter;
jw.setIndent(true);
jw.startDocument();
jw.startElement('root');
jw.writeAttribute('foo', 'value');
jw.text('Some content');
jw.endElement();
jw.endDocument();
console.log(jw.toString());
Output:
{
"version": "1.0",
"encoding": "utf-8",
"root": {
"foo": "value",
"$t": "Some content"
}
}
var JSONWriter = require('json-writer');
jw = new JSONWriter;
jw.startDocument().startElement('root').writeAttribute('foo', 'value').writeElement('tag', 'Some content').endAttribute().endElement().endDocument();
console.log(jw.toString());
Output:
{
"version": "1.0",
"encoding": "utf-8",
"root": {
"foo": "value",
"tag": {
"$t": "Some content"
}
}
}
var JSONWriter = require('json-writer'),
fs = require('fs');
var ws = fs.createWriteStream('/tmp/foo.json');
ws.on('close', function() {
console.log(fs.readFileSync('/tmp/foo.json', 'UTF-8'));
});
jw = new JSONWriter(false, function(string, encoding) {
ws.write(string, encoding);
});
jw.startDocument('1.0', 'UTF-8').startElement(function() {
return 'root';
}).text(function() {
return 'Some content';
}).endElement().endDocument();
ws.end();
Output:
{
"version": "1.0",
"encoding": "UTF-8",
"root": {
"$t": "Some content"
}
}
Use nodeunit to run the tests.
$ npm install nodeunit
$ nodeunit test
Create an new writer
Write text
Create document tag
End current document
Write full element tag
Write full namespaced element tag
Create start namespaced element tag
Create start element tag
End current element
Write full attribute
Write full namespaced attribute
Create start namespaced attribute
Create start attribute
End attribute
Writes a PI
Create start PI tag
End current PI
Write full CDATA tag
Create start CDATA tag
End current CDATA
Do nothing (just here for compatibility with XMLWriter)
Do nothing (just here for compatibility with XMLWriter)
Do nothing (just here for compatibility with XMLWriter)