Skip to content

Instantly share code, notes, and snippets.

@crackcomm
Created March 20, 2013 13:50
Show Gist options
  • Save crackcomm/5204778 to your computer and use it in GitHub Desktop.
Save crackcomm/5204778 to your computer and use it in GitHub Desktop.
My way of serializing cheerio object
# Benchmark
{Benchmark} = require 'benchmark'
suite = new Benchmark.Suite
suite.add("mapList(inputs)",
fn: ->
mapList(inputs)
)
suite.on("cycle", (event, bench) ->
console.log String(event.target)
# console.log String(bench)
)
suite.on("complete", ->
console.log "Fastest is " + @filter("fastest").pluck("name")
)
suite.run async: true
cheerio = require 'cheerio'
f = """<body>
<span class="author vcard"><a href="/MatthewMueller" class="url fn" itemprop="url" rel="author">
<span itemprop="title">MatthewMueller</span>
</a></span></body>
"""
$ = cheerio.load f
inputs = $('body').toArray()
deleteElements = ['prev', 'next', 'parent']
mapList = (elList) ->
mapEl el for el in elList
mapEl = (el) ->
if typeof el is 'object'
deleteElements.forEach (del) -> delete el[del]
el.children = mapList el.children if 'children' of el and el.children?.length > 0
el
inputs = mapList(inputs)
jinputs = JSON.stringify(inputs[0])
# fs.writeFile 'result.json', jinputs
# console.log jinputs
{
"type": "tag",
"name": "body",
"attribs": {},
"children": [
{
"data": "\n",
"type": "text"
},
{
"type": "tag",
"name": "span",
"attribs": {
"class": "author vcard"
},
"children": [
{
"type": "tag",
"name": "a",
"attribs": {
"href": "/MatthewMueller",
"class": "url fn",
"itemprop": "url",
"rel": "author"
},
"children": [
{
"data": "\n",
"type": "text"
},
{
"type": "tag",
"name": "span",
"attribs": {
"itemprop": "title"
},
"children": [
{
"data": "MatthewMueller",
"type": "text"
}
]
},
{
"data": "\n",
"type": "text"
}
]
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment