-
-
Notifications
You must be signed in to change notification settings - Fork 230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
JSON.parse #29
Comments
function parseJSON(jsonStr) {
let index = 0;
const getNextToken = () => jsonStr[index++];
const parseValue = () => {
const token = getNextToken();
if (token === '{') {
return parseObject();
} else if (token === '[') {
return parseArray();
} else if (token === '"') {
return parseString();
} else if (token === 't') {
return true;
} else if (token === 'f') {
return false;
} else if (token === 'n') {
return null;
} else if (!isNaN(token) || token === '-') {
return parseNumber(token);
} else {
throw new SyntaxError('Unexpected token: ' + token);
}
};
const parseObject = () => {
const obj = {};
let key = parseString();
while (getNextToken() !== '}') {
obj[key] = parseValue();
if (jsonStr[index] === ',') {
index++;
key = parseString();
}
}
return obj;
};
const parseArray = () => {
const arr = [];
let token = getNextToken();
while (token !== ']') {
index--;
arr.push(parseValue());
token = getNextToken();
if (token === ',') {
token = getNextToken();
}
}
return arr;
};
const parseString = () => {
let str = '';
let char = getNextToken();
while (char !== '"') {
str += char;
char = getNextToken();
}
return str;
};
const parseNumber = (token) => {
let numStr = token;
while (!isNaN(jsonStr[index]) || jsonStr[index] === '.') {
numStr += getNextToken();
}
return Number(numStr);
};
return parseValue();
} |
JSON.myParse = function (str) {
//实现一
// let a
// eval('a=' + str)
// return a
//实现二
// return new Function(`return ${str}`)()
//实现三
// window._res = null;
// const dom = document.createElement("script");
// dom.innerHTML = `window._res=${str}`;
// document.body.appendChild(dom);
// return window._res;
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: