Skip to content

Instantly share code, notes, and snippets.

@LucienLee
Created March 15, 2017 15:02
Show Gist options
  • Save LucienLee/02b8b1197856a6cd3d9a6c1233f3656d to your computer and use it in GitHub Desktop.
Save LucienLee/02b8b1197856a6cd3d9a6c1233f3656d to your computer and use it in GitHub Desktop.
JsonParser
function JsonParser() {}
JsonParser.prototype.parse = function(inputStr) {
let trimmed = inputStr.replace(/ /g, '')
if (isArray(trimmed)) {
return parseArray(trimmed)
} else if (isObject(trimmed)) {
return parseObj(trimmed)
}
}
function parseObj(str) {
let result = {};
let beginIndex = 0;
str = str.slice(1, str.lastIndexOf('}'))
while (beginIndex < str.length) {
let sepIndex = str.indexOf(':', beginIndex)
let key = str.slice(beginIndex, sepIndex).replace(/\"/g, '')
let value
let next = str.charAt(sepIndex + 1)
if (next === '{' || next === '[') {
let collection = collectJSON(str, sepIndex + 1)
result[key] = new JsonParser().parse(collection.result)
beginIndex = collection.index + 1
} else {
let endIndex = str.indexOf(',', sepIndex) !== -1
? str.indexOf(',', sepIndex)
: str.length
value = str.slice((sepIndex + 1), endIndex)
result[key] = parsePrimitive(value)
beginIndex = endIndex + 1
}
}
return result;
}
function parseArray(str) {
let result = [];
let beginIndex = 0;
str = str.slice(1, str.lastIndexOf(']'));
while (beginIndex < str.length) {
let sepIndex = str.indexOf(',', beginIndex) !== -1
? str.indexOf(',', beginIndex)
: str.length
let item = str.slice(beginIndex, sepIndex)
if (item.indexOf('{') !== -1 || item.indexOf('[') !== -1) {
let collection = collectJSON(str, beginIndex)
result.push(new JsonParser().parse(collection.result))
beginIndex = collection.index + 1
} else {
result.push(parsePrimitive(item))
beginIndex = sepIndex + 1
}
}
return result;
}
function parsePrimitive(str) {
if (str.indexOf('"') !== -1) return String(str)
else if (str.indexOf('.') !== -1) return parseFloat(str)
else return parseInt(str)
}
function collectJSON(str, startIndex) {
let counter = 0
let index = startIndex
let result = ''
do {
let char = str.charAt(index)
if (char === '{' || char === '[') counter++
else if (char === '}' || char === ']') counter--
result += char
index++
} while (counter !== 0)
return {result: result, index: index}
}
function isArray(str) {
return str.length !== 0 && str[0] === '['
}
function isObject(str) {
return str.length !== 0 && str[0] === '{'
}
function main() {
var jsonParser = new JsonParser();
console.log("First Step");
var result = jsonParser.parse(" [ 10, 20, 30.1 ] ");
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
console.log("\nSecond Step");
result = jsonParser.parse(" [ 10 , 20, \"hello\", 30.1 ] ");
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
}
result = jsonParser.parse('{ \
"hello": "world",\
"key1": 20,\
"key2": 20.3,\
"foo": "bar" }');
console.log("\nThird Step");
for (var key in result) {
if (result.hasOwnProperty(key)) {
console.log(key, result[key]);
}
}
result = jsonParser.parse('{\
"hello": "world",\
"key1": 20,\
"key2": {"b": 20.3},\
"foo": {\
"hello1": "world1",\
"key3": [\
[200],\
300]\
} }');
console.log("\nFourth Step");
for (var key in result) {
if (result.hasOwnProperty(key)) {
if (result[key] instanceof Object) {
for (var key2 in result[key]) {
console.log(key2, result[key][key2]);
}
} else {
console.log(key, result[key]);
}
}
}
console.log(result.foo.key3)
}
main();
// Please do not modify the following line.
var module = module || {};
module.exports = JsonParser;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment