Skip to content

Commit

Permalink
json-format
Browse files Browse the repository at this point in the history
  • Loading branch information
luizstacio committed Jul 14, 2014
0 parents commit e2c8c7b
Show file tree
Hide file tree
Showing 3 changed files with 127 additions and 0 deletions.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
json-format
==========

Change for using with npm modules. [original version](https://github.com/phoboslab/json-format).

#### Instaling ####
```
npm install json-format
```

#### Usage ###
```
var jsonFormat = require('./');
var fs = require('fs');
var obj = {
a: 1,
b: 2
}
fs.writeFile('example.json', jsonFormat(obj), function(err){
if (err) throw err;
console.log('saved');
});
```

#### Result ####
```
{
"a": 1,
"b": 2
}
```
64 changes: 64 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
change for npm modules.
by Luiz Estácio.
json-format v.1.1
http://github.com/phoboslab/json-format
Released under MIT license:
http://www.opensource.org/licenses/mit-license.php
*/
var p = [],
push = function( m ) { return '\\' + p.push( m ) + '\\'; },
pop = function( m, i ) { return p[i-1] },
tabs = function( count ) { return new Array( count + 1 ).join( '\t' ); };

function JSONFormat ( json ) {
p = [];
var out = "",
indent = 0;

// Extract backslashes and strings
json = json
.replace( /\\./g, push )
.replace( /(".*?"|'.*?')/g, push )
.replace( /\s+/, '' );

// Indent and insert newlines
for( var i = 0; i < json.length; i++ ) {
var c = json.charAt(i);

switch(c) {
case '{':
case '[':
out += c + "\n" + tabs(++indent);
break;
case '}':
case ']':
out += "\n" + tabs(--indent) + c;
break;
case ',':
out += ",\n" + tabs(indent);
break;
case ':':
out += ": ";
break;
default:
out += c;
break;
}
}

// Strip whitespace from numeric arrays and put backslashes
// and strings back in
out = out
.replace( /\[[\d,\s]+?\]/g, function(m){ return m.replace(/\s/g,''); } )
.replace( /\\(\d+)\\/g, pop ) // strings
.replace( /\\(\d+)\\/g, pop ); // backslashes in strings

return out;
};

module.exports = function(json){
return JSONFormat(JSON.stringify(json));
}
31 changes: 31 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "json-format",
"version": "0.0.1",
"description": "JSON format for good presentation",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "[email protected]:luizstacio/json-format.git"
},
"keywords": [
"json",
"format",
"json",
"pretty",
"json",
"write",
"identation",
"json",
"ident",
"format"
],
"author": "luizstacio",
"license": "MIT",
"bugs": {
"url": "https://github.com/luizstacio/json-format/issues"
},
"homepage": "https://github.com/luizstacio/json-format"
}

0 comments on commit e2c8c7b

Please sign in to comment.