0

I have user-specified input that looks like this:

outerObject = {};
outerObject.innerObject = {};
outerObject.innerObject.key = 'value';
outerObject.innerObject.exampleTwo = 2;

Repeat that general pattern for a couple thousand lines, and you see how this looks a little tedious and is hard to maintain. What I'd like to do is output these lines into something like this:

outerObject = {
    innerObject: {
        key: 'value',
        exampleTwo: 2
    }
};

Is there an existing library to convert the single-line object creations into the block creation shown above? And if not, mind taking a stab at code that could? I'm so fundamentally confused at where to start that I can't even figure out how to nest objects, so any help would be great.

EDIT: I stumbled upon this accepted answer for a different issue. It appears to format an object the way I want after splitting the value and key from each of the four lines in that first block. It does not include any sort of output formatting, however...

Community
  • 1
  • 1
rydash
  • 301
  • 3
  • 12
  • 1
    I don't understand the question; are you trying to manipulate _text that looks like JavaScript_? – Evan Davis Jan 25 '16 at 21:50
  • That's correct. I'm taking existing JavaScript text and trying to format it into what appears to be equivalent text, just using object notation. – rydash Jan 25 '16 at 21:51
  • You could just get the outerObject in the browser console (if it all just JSON-like static content in that object, that is) – Kerstomaat Jan 25 '16 at 22:03
  • 1
    What format is the user-specified input in? Is it actually JavaScript, or something else? If it’s actually JavaScript, use a JavaScript parser – https://github.com/ternjs/acorn, maybe? – Ry- Jan 25 '16 at 22:31

1 Answers1

1

This method only works when all objects are static/JSON-like, meaning no functions or anything

You could just evaluate your input like this in the browser (or the browser console or any js context, like Node):

<script>
    outerObject = {};
    outerObject.innerObject = {};
    outerObject.innerObject.key = 'value';
    outerObject.innerObject.exampleTwo = 2;
</script>

Then just JSON.stringify(outerObject, null, ' ') which will return

"{
    "innerObject": {
        "key": "value",
        "exampleTwo": 2
    }
}"

All you do next is append "outerObject = " in front

Kerstomaat
  • 673
  • 4
  • 13