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.stringify #28

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

JSON.stringify #28

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

Comments

@Sunny-117
Copy link
Owner

function toJSON(data){

}

// test
toJSON(""); // -> ""
toJSON("abc"); // -> "abc"
toJSON(123); // -> 123
toJSON({a:1, b:2}); // -> {"a":1, "b":2}
toJSON(["1", 3, {name:"monica", age:18}]); //-> ["1", 3, {"name":"monica", "age":18}]
@kangkang123269
Copy link

kangkang123269 commented Feb 20, 2023

function toJSON(obj) {
  if (typeof obj === 'string') {
    return `"${obj}"`;
  }

  if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null) {
    return String(obj);
  }

  if (Array.isArray(obj)) {
    return `[${obj.map(item => toJSON(item)).join(',')}]`;
  }

  if (typeof obj === 'object') {
    const keys = Object.keys(obj);
    return `{${keys.map(key => `"${key}":${toJSON(obj[key])}`).join(',')}}`;
  }

  return undefined;
}

@gswysy
Copy link

gswysy commented Mar 28, 2024

JSON.myStringify = function (e) {
    if (typeof e === 'number' || typeof e === 'boolean' || e === null) return String(e)
    if (typeof e === 'string') return `"${e}"`
    if (e !== e) return null
    if (e.constructor === RegExp) return '{}'
    if (e.constructor === Date) return `"${e.toString()}"`
    if (Array.isArray(e)) {
        return `[${e.map(item=>JSON.myStringify(item)).join(',')}]`
    }
    if (typeof e === 'object') {
        return `{${Object.keys(e).map(item=>`"${item}":${JSON.stringify(e[item])}`).join(',')}}`
    }
    return undefined
}

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