Code Monkey home page Code Monkey logo

himalaya's Introduction

Himalaya

Parse HTML into JSON

npm Build Status Coverage Status Greenkeeper badge

Try online ๐Ÿš€

Usage

Node

npm install himalaya
var himalaya = require('himalaya')
var html = require('fs').readFileSync('/webpage.html', {encoding: 'utf8'})
var json = himalaya.parse(html)
console.log('๐Ÿ‘‰', json)

Browser

Download himalaya.js and put it in a <script> tag. Himalaya will be accessible from window.himalaya.

var html = "<div>Hello world</div>"
var json = himalaya.parse(html)
console.log('๐Ÿ‘‰', json)

Himalaya can be bundled with your code using tools like Browersify and Webpack.

Command-line

Himalaya includes a command-line tool.

npm install --global himalaya
himalaya webpage.html webpage.json
# or as a pipe
echo "<h1>Hello</h1>" | himalaya > hello.json

Run himalaya --help for more information.

Parser AST Specification

Himalaya has a specification for its output. Essentially, everything is a node and can either be an Element, Comment, or Text node. The full specification provides the complete details.

Example Input/Output

<div class='post post-featured'>
	<p>Himalaya parsed me...</p>
	<!-- ...and I liked it. -->
</div>
[
  {
    "type": "Element",
    "tagName": "div",
    "attributes": {
      "className": [
        "post",
        "post-featured"
      ]
    },
    "children": [
      {
        "type": "Element",
        "tagName": "p",
        "attributes": {},
        "children": [
          {
            "type": "Text",
            "content": "Himalaya parsed me..."
          }
        ]
      },
      {
        "type": "Comment",
        "content": " ...and I liked it. ",
      }
    ]
  }
]

Note: Text nodes consisting of whitespace are not shown for readability.

Features

Synchronous

Himalaya transforms HTML into JSON, that's it. Himalaya is synchronous and does not require any complicated callbacks.

Parses Attributes

Himalaya does a couple transformations when processing attributes:

  • Camel-cases attribute names
  • Attributes without values use their names as values. For example, disabled turns into disabled="disabled"
  • Groups data-* attributes into a dataset object
  • Attempts to cast any value to a number if !Nan
  • Parses the style attribute into a hash map

Handles Weirdness

Himalaya handles a lot of HTML's fringe cases, like:

  • Closes unclosed tags <p><b>...</p>
  • Ignores extra closing tags <span>...</b></span>
  • Properly handles void tags like <meta> and <img>
  • Properly handles self-closing tags like <input/>
  • Handles <!doctype> and <-- comments -->
  • Does not parse the contents of <script>, <style>, and HTML5 <template> tags

Preserves Whitespace

Himalaya does not cut corners and returns an accurate representation of the HTML supplied. To remove whitespace, post-process the JSON; check out an example script.

Going back to HTML

Himalaya provides translation functions that can take the Himalaya AST and output HTML and Jade.

The following example does nothing. It parses the HTML to JSON then parses the JSON back into HTML, which is the exact same as the original. Himalaya does buff out the kinks of malformed originals.

var fs = require('fs')
var himalaya = require('himalaya')
var toHTML = require('himalaya/translate').toHTML

var html = fs.readFileSync('/webpage.html', {encoding: 'utf8'})
var json = himalaya.parse(html)
fs.writeFileSync('/webpage.html', toHTML(json))

Translation supports Jade/Pug using toJade/toPug. See the reference document for translations.

Why "Himalaya"?

First, my friends weren't helpful. Except Josh, Josh had my back.

While I was testing the parser, I threw a download of my Twitter homepage in and got a giant JSON blob out. My code editor Sublime Text has a mini-map and looking at it sideways the data looked like a never-ending mountain range. Also, "himalaya" has H, M, L in it.

Implementation

My first implementation used look-ahead, found the matching closing tag, and then recursively parsed the inners until a tree results. That was problematic. This implementation uses no look-ahead and instead uses a stack to keep track of nesting while processing the source HTML. At an end tag the stack it cut to match and then parsing picks up again at the higher level.

This parser runs without using any regular expressions. Since I wanted this to double as a learning resource, I wanted the code to be readable sans regexes.

Contributing

We can always have more tests: if you find a bug, create an issue or be fabulous and fix the problem and write the tests up yourself in a coherent pull request.

Run tests with the npm test command.

Follow me on Twitter for updates or for the lolz and please check out my other repositories if I have earned it. I thank you for reading.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.