stream-stringify
v2.3.3
Published
Stringify nested JSON through streams.
Downloads
68
Maintainers
Readme
Create streams for nested JSON structures of which you don't know about on beforehand.
Cheaper than JSON.stringify
which always will buffers the entire object.
Example
jsonString = ''
root = sstringify().on('data', (data) -> jsonString += data)
root.writeKeyValue "firstKey", "firstValue"
nestedObject = root.startNewObject "nestedObject"
innerArray = nestedObject.startNewArray "innerArray"
innerArray.writeElement 1
innerArray.writeElement [2,3]
innerArray.stop()
nestedObject.writeKeyValue "anotherInnerKey", "anotherInnerValue"
nestedObject.stop()
root.stop()
jsonString
is now:
{
"firstKey": "firstValue",
"nestedObject": {
"innerArray": [
1,
[
2,
3
]
],
"anotherInnerKey": "anotherInnerValue"
}
}
Functionality
This stream supports functionality found in most streams, such as write()
, end()
, or
destroy()
. The methods described below are specific for this stream.
sstringify(options)
Constructs the root of the JSON structure. When specified, the following options change the behaviour of the stream:
type
- String specifying the type of the stream root.Object
(Default) An object with key-value pairsArray
An array with arbitrary content
prettyFormat
- Boolean specifying whether the object should be formatted beautifully.tabWidth
- IfprettyFormat
istrue
, then this is the number of spaces. Defaults to2
.autoDestroy
- Boolean specifying whether the object should be destroyed when ended. Default istrue
.
startNewObject(key)
Starts a new object stream which is connected to the specfied key
. Returns the stream. When using an array, do not specify key
.
startNewArray(key)
Starts a new array stream which is connected to the specfied key
. Returns the stream. When using an array, do not specify key
.
stop()
Notifies the stream that there won't be more information. This will close the bracket. The stream will automatically be ended and destroyed when not used by other streams (unless autoDestroy=false
).
writeKeyValue(key,value)
Writes a key and a value to the stream. Does not work when working with an array.
writeElement(element)
Writes an element to the stream. Does not work when working with an object.
Set it off!
npm install stream-stringify