• This repository has been archived on 04/Dec/2018
  • Stars
    star
    1,900
  • Rank 23,551 (Top 0.5 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 12 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

rawStream.pipe(JSONStream.parse()).pipe(streamOfObjects)

JSONStream

streaming JSON.parse and stringify

install

npm install JSONStream

example

var request = require('request')
  , JSONStream = require('JSONStream')
  , es = require('event-stream')

request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
  .pipe(JSONStream.parse('rows.*'))
  .pipe(es.mapSync(function (data) {
    console.error(data)
    return data
  }))

JSONStream.parse(path)

parse stream of values that match a path

  JSONStream.parse('rows.*.doc')

The .. operator is the recursive descent operator from JSONPath, which will match a child at any depth (see examples below).

If your keys have keys that include . or * etc, use an array instead. ['row', true, /^doc/].

If you use an array, RegExps, booleans, and/or functions. The .. operator is also available in array representation, using {recurse: true}. any object that matches the path will be emitted as 'data' (and piped down stream)

If path is empty or null, no 'data' events are emitted.

If you want to have keys emitted, you can prefix your * operator with $: obj.$* - in this case the data passed to the stream is an object with a key holding the key and a value property holding the data.

Examples

query a couchdb view:

curl -sS localhost:5984/tests/_all_docs&include_docs=true

you will get something like this:

{"total_rows":129,"offset":0,"rows":[
  { "id":"change1_0.6995461115147918"
  , "key":"change1_0.6995461115147918"
  , "value":{"rev":"1-e240bae28c7bb3667f02760f6398d508"}
  , "doc":{
      "_id":  "change1_0.6995461115147918"
    , "_rev": "1-e240bae28c7bb3667f02760f6398d508","hello":1}
  },
  { "id":"change2_0.6995461115147918"
  , "key":"change2_0.6995461115147918"
  , "value":{"rev":"1-13677d36b98c0c075145bb8975105153"}
  , "doc":{
      "_id":"change2_0.6995461115147918"
    , "_rev":"1-13677d36b98c0c075145bb8975105153"
    , "hello":2
    }
  },
]}

we are probably most interested in the rows.*.doc

create a Stream that parses the documents from the feed like this:

var stream = JSONStream.parse(['rows', true, 'doc']) //rows, ANYTHING, doc

stream.on('data', function(data) {
  console.log('received:', data);
});
//emits anything from _before_ the first match
stream.on('header', function (data) {
  console.log('header:', data) // => {"total_rows":129,"offset":0}
})

awesome!

In case you wanted the contents the doc emitted:

var stream = JSONStream.parse(['rows', true, 'doc', {emitKey: true}]) //rows, ANYTHING, doc, items in docs with keys

stream.on('data', function(data) {
  console.log('key:', data.key);
  console.log('value:', data.value);
});

You can also emit the path:

var stream = JSONStream.parse(['rows', true, 'doc', {emitPath: true}]) //rows, ANYTHING, doc, items in docs with keys

stream.on('data', function(data) {
  console.log('path:', data.path);
  console.log('value:', data.value);
});

recursive patterns (..)

JSONStream.parse('docs..value') (or JSONStream.parse(['docs', {recurse: true}, 'value']) using an array) will emit every value object that is a child, grand-child, etc. of the docs object. In this example, it will match exactly 5 times at various depth levels, emitting 0, 1, 2, 3 and 4 as results.

{
  "total": 5,
  "docs": [
    {
      "key": {
        "value": 0,
        "some": "property"
      }
    },
    {"value": 1},
    {"value": 2},
    {"blbl": [{}, {"a":0, "b":1, "value":3}, 10]},
    {"value": 4}
  ]
}

JSONStream.parse(pattern, map)

provide a function that can be used to map or filter the json output. map is passed the value at that node of the pattern, if map return non-nullish (anything but null or undefined) that value will be emitted in the stream. If it returns a nullish value, nothing will be emitted.

JSONStream also emits 'header' and 'footer' events, the 'header' event contains anything in the output that was before the first match, and the 'footer', is anything after the last match.

JSONStream.stringify(open, sep, close)

Create a writable stream.

you may pass in custom open, close, and seperator strings. But, by default, JSONStream.stringify() will create an array, (with default options open='[\n', sep='\n,\n', close='\n]\n')

If you call JSONStream.stringify(false) the elements will only be seperated by a newline.

If you only write one item this will be valid JSON.

If you write many items, you can use a RegExp to split it into valid chunks.

JSONStream.stringifyObject(open, sep, close)

Very much like JSONStream.stringify, but creates a writable stream for objects instead of arrays.

Accordingly, open='{\n', sep='\n,\n', close='\n}\n'.

When you .write() to the stream you must supply an array with [ key, data ] as the first argument.

unix tool

query npm to see all the modules that browserify has ever depended on.

curl https://registry.npmjs.org/browserify | JSONStream 'versions.*.dependencies'

numbers

numbers will be emitted as numbers. huge numbers that cannot be represented in memory as javascript numbers will be emitted as strings. cf https://github.com/creationix/jsonparse/commit/044b268f01c4b8f97fb936fc85d3bcfba179e5bb for details.

Acknowlegements

this module depends on https://github.com/creationix/jsonparse by Tim Caswell and also thanks to Florent Jaby for teaching me about parsing with: https://github.com/Floby/node-json-streams

license

Dual-licensed under the MIT License or the Apache License, version 2.0

More Repositories

1

event-stream

EventStream is like functional programming meets IO
JavaScript
2,189
star
2

JSON.sh

a pipeable JSON parser written in Bash
Shell
1,981
star
3

scuttlebutt

peer-to-peer replicatable data structure
JavaScript
1,310
star
4

rc

The non-configurable configuration loader for lazy people.
JavaScript
995
star
5

crdt

Commutative Replicated Data Types for easy collaborative/distributed systems.
JavaScript
836
star
6

through

simple way to create a ReadableWritable stream that works
JavaScript
667
star
7

your-web-app-is-bloated

measuring memory usage of popular webapps
514
star
8

npmd

JavaScript
450
star
9

split

JavaScript
346
star
10

curry

simple curry module, with nothing *too clever*, and full test coverage
JavaScript
314
star
11

random-name

JavaScript
296
star
12

hashlru

JavaScript
237
star
13

wifi.sh

Shell
216
star
14

level-sublevel

no longer maintained, sorry!
JavaScript
194
star
15

mux-demux

mutiplex-demultiplex multiple streams through a single text Stream
JavaScript
179
star
16

noderify

official fork: https://github.com/staltz/noderify
JavaScript
157
star
17

feedopensource

Iteratively Fund Open Source Projects With Bitcoin
JavaScript
142
star
18

excel-stream

JavaScript
137
star
19

stream-spec

executable specification for Stream (make testing streams easy)
JavaScript
125
star
20

map-stream

JavaScript
122
star
21

map-reduce

async map-reduce functions for nodejs
JavaScript
121
star
22

cyphernet

115
star
23

observable

A Mutable Value represented as a Function.
HTML
111
star
24

stream-combiner

JavaScript
103
star
25

rpc-stream

JavaScript
98
star
26

bench-lru

JavaScript
85
star
27

pull-box-stream

One way streaming encryption based on libsodium's secretbox primitive
JavaScript
84
star
28

level-live-stream

JavaScript
79
star
29

stack-expression

inspired by regular expressions but can do nested structures
JavaScript
77
star
30

hipster

JavaScript
72
star
31

snob

distributed version control system implemented in javascript.
JavaScript
71
star
32

xdiff

diff complex javascript objects
JavaScript
70
star
33

from

Easy way to create a Readable Stream
JavaScript
70
star
34

scalable-secure-scuttlebutt

HTML
68
star
35

explain-error

JavaScript
67
star
36

fsm

Finite State Machines in javascript
JavaScript
66
star
37

r-edit

JavaScript
64
star
38

readme

JavaScript
62
star
39

tiles

JavaScript
61
star
40

indexhtmlify

JavaScript
59
star
41

tacodb

JavaScript
57
star
42

adiff

diff and patch operations on arrays.
JavaScript
57
star
43

map-filter-reduce

JavaScript
57
star
44

browser-stream

open pipable streams to and from the browser, with Socket.io
JavaScript
55
star
45

reconnect

JavaScript
53
star
46

electro

JavaScript
51
star
47

level-replicate

JavaScript
51
star
48

d64

JavaScript
50
star
49

on-change-network

JavaScript
49
star
50

lock

lock asynchronous resources
JavaScript
47
star
51

crypto-bench

HTML
47
star
52

monotonic-timestamp

JavaScript
44
star
53

mynosql

JavaScript
44
star
54

pause-stream

JavaScript
43
star
55

json-select

JavaScript
43
star
56

json-buffer

JavaScript
41
star
57

bittodo

JavaScript
40
star
58

stream-punks

discussion repo for streams
39
star
59

charwise

JavaScript
39
star
60

proxy-by-url

custom logic for node-http-proxy to proxy based on incoming url
JavaScript
38
star
61

sentimental-versioning

version numbers with meaning
HTML
38
star
62

coherence

JavaScript
38
star
63

level-hooks

JavaScript
37
star
64

sodium-browserify

JavaScript
37
star
65

secret-handshake-paper

TeX
36
star
66

browselectrify

create browserify bundle that also works in electron
JavaScript
36
star
67

kv

simple kv store for streams
JavaScript
35
star
68

c2wasm

C++
35
star
69

level-trigger

triggers for levelup
JavaScript
33
star
70

deploy

scripts to setup continuous deployment with git push
Shell
33
star
71

presentations

JavaScript
32
star
72

rumours

Intergration of scuttlebutt family.
JavaScript
32
star
73

web-bootloader

HTML
28
star
74

remote-events

connect EventEmitters through Streams.
JavaScript
28
star
75

indexes-of

JavaScript
27
star
76

mpg123

JavaScript
27
star
77

level-master

JavaScript
27
star
78

what-is-scuttlebutt

spec for defining "scuttlebutt" as a living changing protocol
27
star
79

h

JavaScript
26
star
80

testbed

continuous integration for nodejs
JavaScript
25
star
81

canvas-browserify

HTML
25
star
82

level-merkle

JavaScript
25
star
83

it-is

assertion DSL based on functional idioms.
JavaScript
25
star
84

semver-ftw

Simple Description of SemVer
HTML
25
star
85

level-inverted-index

JavaScript
24
star
86

computer-modern

CSS
24
star
87

hyperaudio

JavaScript
24
star
88

level-scuttlebutt

leveldb persistence for scuttlebutts (scuttlebutt/crdt/append-only and friends)
JavaScript
24
star
89

level-search

JavaScript
24
star
90

level-couch-sync

JavaScript
23
star
91

simple-xlsx

maintained fork is at https://github.com/zeke/simple-xlsx
JavaScript
23
star
92

content-addressable-store

JavaScript
23
star
93

shasum

JavaScript
23
star
94

ticket-auth

JavaScript
22
star
95

ssh-key-to-pem

JavaScript
21
star
96

private-groups-paper

21
star
97

scuttlebucket

JavaScript
21
star
98

looper

JavaScript
20
star
99

deterministic-tar

JavaScript
20
star
100

npm-browserify

JavaScript
20
star