Skip to content

Instantly share code, notes, and snippets.

@domoritz
Last active June 28, 2018 04:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domoritz/259b881c162c5618c7b8c22682521769 to your computer and use it in GitHub Desktop.
Save domoritz/259b881c162c5618c7b8c22682521769 to your computer and use it in GitHub Desktop.
JS to JSON
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>
body { margin:0; font-family: sans-serif}
h2 {margin: 0}
.wrapper {display: flex; flex-direction: row; justify-content: space-between; }
.wrapper div {flex: 1;}
.wrapper div:last-child {padding-left: 20px}
#error {color: firebrick}
textarea {height: 400px; width: 99%}
</style>
</head>
<body>
<div class="wrapper">
<div>
<h2>JS:</h2><br>
<textarea id="in">{
hello: 42,
world: 1+2,
data: {
a: [1,2,3,4,5],
b: [6,7,8,9,10],
c: [11,12,13,14,15],
d: [16,17,17,19,20]
},
awesome: true
}
</textarea>
</div>
<div>
<h2>JSON:</h2><br>
<textarea id="out"></textarea>
</div>
</div>
<p id="error"></p>
<script src="stringify.js"></script>
<script>
const input = document.getElementById("in");
const output = document.getElementById("out");
const error = document.getElementById("error");
function run(){
try {
const json = stringify(eval('x=' + input.value));
output.value = json;
error.innerText = "";
} catch (err) {
error.innerText = err.toString();
output.value = "";
}
}
window.onload = function() {
input.addEventListener('input', run);
run();
};
</script>
</body>
// from json-stringify-pretty-compact
function stringify (obj, options) {
options = options || {}
var indent = JSON.stringify([1], null, get(options, 'indent', 2)).slice(2, -3)
var addMargin = get(options, 'margins', false)
var maxLength = (indent === '' ? Infinity : get(options, 'maxLength', 80))
return (function _stringify (obj, currentIndent, reserved) {
if (obj && typeof obj.toJSON === 'function') {
obj = obj.toJSON()
}
var string = JSON.stringify(obj)
if (string === undefined) {
return string
}
var length = maxLength - currentIndent.length - reserved
if (string.length <= length) {
var prettified = prettify(string, addMargin)
if (prettified.length <= length) {
return prettified
}
}
if (typeof obj === 'object' && obj !== null) {
var nextIndent = currentIndent + indent
var items = []
var delimiters
var comma = function (array, index) {
return (index === array.length - 1 ? 0 : 1)
}
if (Array.isArray(obj)) {
for (var index = 0; index < obj.length; index++) {
items.push(
_stringify(obj[index], nextIndent, comma(obj, index)) || 'null'
)
}
delimiters = '[]'
} else {
Object.keys(obj).forEach(function (key, index, array) {
var keyPart = JSON.stringify(key) + ': '
var value = _stringify(obj[key], nextIndent,
keyPart.length + comma(array, index))
if (value !== undefined) {
items.push(keyPart + value)
}
})
delimiters = '{}'
}
if (items.length > 0) {
return [
delimiters[0],
indent + items.join(',\n' + nextIndent),
delimiters[1]
].join('\n' + currentIndent)
}
}
return string
}(obj, '', 0))
}
// Note: This regex matches even invalid JSON strings, but since we’re
// working on the output of `JSON.stringify` we know that only valid strings
// are present (unless the user supplied a weird `options.indent` but in
// that case we don’t care since the output would be invalid anyway).
var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,\][}{]/g
function prettify (string, addMargin) {
var m = addMargin ? ' ' : ''
var tokens = {
'{': '{' + m,
'[': '[' + m,
'}': m + '}',
']': m + ']',
',': ', ',
':': ': '
}
return string.replace(stringOrChar, function (match, string) {
return string ? match : tokens[match]
})
}
function get (options, name, defaultValue) {
return (name in options ? options[name] : defaultValue)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment