JSON stream is a convenient format for streaming data - it follows an array of objects structure with the outermost brackets [] implied and uses newlines as record separators instead of commas. In essence, it's like a continuous flow of lines where each line represents a JSON object. The specification does not explicitly mention if a line can be an array itself, though arrays can be embedded within objects.
Consider the example given in the specification; you would likely encounter a similar text stream:
{"string":"value"}
{"number":42,"boolean":true,"nested":{"objects":["within","arrays"]}}
{"another":{"example":"data"}}
If you were to receive this data and store it in a variable named input
, which essentially holds a string, you could divide it into separate lines using input.split('\n')
. Afterward, each line could be parsed individually using JSON.parse(…)
and stored in an array.
let input = '{"string":"value"}\n{"number":42,"boolean":true,"nested":{"objects":["within","arrays"]}}\n{"another":{"example":"data"}}';
let result = input.split('\n').map(line => JSON.parse(line));
console.log('The resulting array of elements:');
console.log(result);
console.log('Each element separately:');
for (item of result) {
console.log("element:", item);
}