0

Say for example if I have a 3 level deep javascript object

{CONN_INFO: {CFGSwitch: {412: {}}}}

How can I write a function that determines if it is nested? And secondly, how can I then convert the empty object {} to a string such as "{}"

3
  • 1
    If you really mean JSON, your syntax is incorrect. JSON requires all property names to be inside "double quotes". Commented May 8, 2017 at 4:55
  • {} is not a null value. It is an empty object. If you alert({}==null) you will get false. Commented May 8, 2017 at 4:57
  • Sorry, thanks for that. I've updated the original. Commented May 8, 2017 at 5:04

2 Answers 2

1

How can I write a function that determines if it is nested?

For all keys of the current object, check its type, if JSON then nesting is present.

And secondly, how can I then convert the empty object {} to a string such as "{}"?

If you encounter a nested JSON object, check for its key length using Object.keys(currentJSONObj).length, if 0 then this is an empty JSON. So re-assign "{}" to the key which had empty JSON object at first place.

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

2 Comments

Would I have to use a recursive function for the second part? Any idea how I could write it? I've now got a function to check how deep the nesting is.
Yes.. Recursive function is the answer. Call it for every key within the object, if the value of that key is JSON again, recur!
0

Iterate and check Object.keys(current_obj).length

Comments

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.