Skip to content

JSON.stringify实现 #37

@CodeDreamfy

Description

@CodeDreamfy

主要思路是递归

var toStringify = json => {
    switch(typeof json) {
        case 'undefined':
            return ""
        case 'string':
            return `"${json}"`
        case 'number':
            return `${json}`;
        case 'boolean':
            return json ? "true" : "false"
        default:
            if(json === null) {
                return  "null";
            }else if(Array.isArray(json)) {
                return `[${json.map(toStringify).join(',')}]`
            } else {
                 return `{${Object.keys(json).map(key => `"${key}":${toStringify(json[key])}`).join(',')}}`
            }
    }
}
var json = {
  x: 1,
  y: [1, "str", true, { name: 'yiyi'}],
  z: {
    a: 1,
    b: null
  }
};
var s = JSON.stringify(json);
var s1 = stringify(json);
var s2 = toStringify(json);

console.log(s); // {"x":1,"y":[1,"str",true,{"name":"yiyi"}],"z":{"a":1,"b":null}}
console.log(s2); // {"x":1,"y":[1,"str",true,{"name":"yiyi"}],"z":{"a":1,"b":null}}
console.log(JSON.parse(s2));

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions