0

I have tried this but it is not working properly. It is just giving regular JS string and not in the JSON format

function convert(obj) {
  let ret = "{";

  for (let k in obj) {
    let v = obj[k];

    if (typeof v === "function") {
      v = v.toString();
    } else if (v instanceof Array) {
      v = JSON.stringify(v);
    } else if (typeof v === "object") {
      v = convert(v);
    } else {
      v = `"${v}"`;
    }

    ret += `\n  ${k}: ${v},`;
  }

  ret += "\n}";

  return ret;
}

Input:

const input = {
 rules3: {
    fn1: ()=> {
     setTimeout(function abc() {console.log("aaaaaaaa")}, 3000);
    }
  }
}

Expected output:

I need to JSON.parse the converted String back. So below is an example of expected output

'const input = {
 "rules3": {
    "fn1": ()=> {
     "setTimeout(function abc() {console.log("aaaaaaaa")}, 3000)"
    }
  }
}'

3
  • Can you please add input and expected output as well? Commented Jan 13, 2023 at 7:42
  • This is example object: const input = { rules3: { fn1: ()=> { setTimeout(function abc() {console.log("aaaaaaaa")}, 3000); } } } Commented Jan 13, 2023 at 7:44
  • 2
    Is there a reason why you can't use JSON.stringify() on your object. You don't typically need to stringify functions, just the object data is enough Commented Jan 13, 2023 at 7:44

1 Answer 1

1

As you know, JSON does not support functions and regex. It looks like you want to stringify the function, and store as JSON. Instead of handcrafting a stringify function you can use the JSON.stringify() function with a replacer helper function:

const input = {
  text: 'hi',
  numbner: 123,
  array: [1, 2, 3],
  regex: /^-?\d+(:?\.\d+)?$/,
  rules3: {
    fn1: () => {
      setTimeout(function abc() {
        console.log("aaaaaaaa")
      }, 3000);
    }
  }
}

function replacer(key, val) {
  if (typeof val === 'function' || val && val.constructor === RegExp) {
    return val.toString();
  }
  return val;
}

console.log(JSON.stringify(input, replacer, 2))

Output:

{
  "text": "hi",
  "numbner": 123,
  "array": [
    1,
    2,
    3
  ],
  "regex": "/^-?\\d+(:?\\.\\d+)?$/",
  "rules3": {
    "fn1": "() => {\n      setTimeout(function abc() {\n        console.log(\"aaaaaaaa\")\n      }, 3000);\n    }"
  }
}

In the same way you can use a replacer function to restore the object using JSON.parse().

Note that because the function and regex are turned into a string it is not deterministic what is a string, what is a function, and what is a regex. Hence you might want to annotate the stringified function and regex to make it deterministic.

Docs:

Sign up to request clarification or add additional context in comments.

2 Comments

@PeterTheony I am having issues with writing replacer function on parse. Could you please post the code?
@AdityaBVijay: Can you show in your question what you have tried? SO is not a free service to produce code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.