Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

JSON.parse #29

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

// eval 实现
var json = '{"a":"1", "b":2}';
var obj = eval("(" + json + ")");  // obj 就是 json 反序列化之后得到的对象
// New Function
var json = '{"name":"小姐姐", "age":20}';
var obj = (new Function('return ' + json))();
@kangkang123269
Copy link

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();
}

@gswysy
Copy link

gswysy commented Mar 28, 2024

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants