|
| 1 | +/*! JSON.minify() |
| 2 | + v0.1 (c) Kyle Simpson |
| 3 | + MIT License |
| 4 | +*/ |
| 5 | + |
| 6 | +JSON.minify() minifies blocks of JSON-like content into valid JSON by removing all |
| 7 | +whitespace *and* comments. |
| 8 | + |
| 9 | +JSON parsers (like JavaScript's JSON.parse() parser) generally don't consider JSON |
| 10 | +with comments to be valid and parseable. So, the intended usage is to minify |
| 11 | +development-friendly JSON (with comments) to valid JSON before parsing, such as: |
| 12 | + |
| 13 | +JSON.parse(JSON.minify(str)); |
| 14 | + |
| 15 | +Now you can maintain development-friendly JSON documents, but minify them before |
| 16 | +parsing or before transmitting them over-the-wire. |
| 17 | + |
| 18 | +Though comments are not officially part of the JSON standard, this post from |
| 19 | +Douglas Crockford back in late 2005 helps explain the motivation behind this project. |
| 20 | + |
| 21 | +http://tech.groups.yahoo.com/group/json/message/152 |
| 22 | + |
| 23 | +"A JSON encoder MUST NOT output comments. A JSON decoder MAY accept and ignore comments." |
| 24 | + |
| 25 | +Basically, comments are not in the JSON *generation* standard, but that doesn't mean |
| 26 | +that a parser can't be taught to ignore them. Which is exactly what JSON.minify() |
| 27 | +is for. |
| 28 | + |
| 29 | +The first implementation of JSON.minify() is in JavaScript, but the intent is to |
| 30 | +port the implementation to as many other environments as possible/practical. |
| 31 | + |
| 32 | +---------- |
| 33 | +To use in node via npm: |
| 34 | + |
| 35 | +npm install node-json-minify |
| 36 | + |
| 37 | +Then in code: |
| 38 | + |
| 39 | +JSON.minify = JSON.minify || require("node-json-minify"); |
| 40 | + |
| 41 | +var myjson = JSON.minify( '{ /* comment */ "foo": 42 \n }' ); // {"foo":42} |
| 42 | +---------- |
| 43 | + |
| 44 | +NOTE: As transmitting bloated (ie, with comments/whitespace) JSON would be wasteful |
| 45 | +and silly, this JSON.minify() is intended for use in server-side processing |
| 46 | +environments where you can strip comments/whitespace from JSON before parsing |
| 47 | +a JSON document, or before transmitting such over-the-wire from server to browser. |
0 commit comments