-3

Given a string I need to create an object and convert that string to properties.

So given this:

"anchor: true,
text: 'primary button',
style: 'primary'
"

I need to generate a real object:

{
     anchor: true,
     text: 'primary button',
     style: 'primary'
}

Any help on this of course greatly appreciated.

4
  • 2
    If you create valid JSON strings, this would be trivial, now you'd made into a nightmare and have to write your own parser. Commented Jan 13, 2015 at 18:30
  • (This will probably go better if showing an attempt - and the problem(s) that results from it - or at least pointing out approaches explored and why they are not suitable.) Commented Jan 13, 2015 at 18:30
  • @adeneo But MD/YAML != JSON. Commented Jan 13, 2015 at 18:32
  • 1
    anObject=eval("0||{"+yourString+"}") Commented Jan 13, 2015 at 18:37

2 Answers 2

0

This depends on the markdown format. If it is Yaml (which it looks like), you will need to use a yaml parser such as js-yaml (https://github.com/nodeca/js-yaml).

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

1 Comment

Thank you but the markdown is not relevant. It is just where the string is coming from.
0

Thanks to @dandavis for posting this answer in a comment:

anObject=eval("0||{"+yourString+"}")

1 Comment

I couldn't bring myself to put eval() in an answer, and i would probably get beat up if i did. A lot of people don't like eval for a lot of reasons, most of them trivial, but some worth considering. I would say that as long as you don't eval() user input, and you don't need to run with "es3 compact profile"-level support (ala chrome extensions), eval() will be the simplest way to do what you want with controlled input.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.