0

I have this string "{ min: 1, max: 10, precision: 3 }"

I want to convert that just to be { min: 1, max: 10, precision: 3 } so I can pass that as an argument to some function faker.random.number({ min: 1, max: 10, precision: 3 })

How would you do the conversion in such case?

UPDATE: when I am using eval("faker.random.number({ min: 0, max: 10, precision: 1 })") I am getting error faker is not defined.

9
  • JSON.parse (w3schools.com/js/js_json_parse.asp)? Commented Oct 15, 2018 at 22:04
  • 2
    @DaleBurrell—it's not valid JSON, and please don't reference w3schools. MDN and ECMA-262 are much better references. Commented Oct 15, 2018 at 22:21
  • But you could easily convert it to JSON. Commented Oct 15, 2018 at 22:23
  • Parsing it to JSON would likely be no easier than parsing it to an object without using JSON.parse. Commented Oct 15, 2018 at 22:27
  • @RobG w3schools is now recognized as a fine resource for lots of things Commented Oct 15, 2018 at 22:41

4 Answers 4

1

Short answer: eval.

Long answer: Don't use eval. Make your data in a standardized format (such as JSON) and use tools to parse said standardized format (such as JSON.parse())

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

1 Comment

I don't think eval would help here. I just tried it in stackblitz and it returns Error: unexpected token: ':' UPDATE: Actually I forgot to include () around the value in a string. It works fine.
1

You could use eval with something like:

faker.random.number(eval('void 0,' + '{ min: 1, max: 10, precision: 3 }'));

The 'void 0, part is necessary as if { is encountered as the first token in a statement, it's treated as the start of a block, not an object literal.

Anyway, you want to avoid eval so you'll have to parse the string manually. Hopefully it doesn't get too complex and you can keep it simple like the following, which can handle values that are strings or numbers but not much else:

var s = '{ min: 1, max: 10, precision: 3 }';

function simpleParse(s) {

  // Remove unwanted characters, split into name:value pairs on ,
  let parts = s.replace(/[ {}]/g,'').split(',');

  // Split properties on : and keep strings as strings, assume
  // anything else is a number
  return parts.reduce((acc, part) => {
    let [prop, value] = part.split(':');
    acc[prop] = /[\'\"]/.test(value)? value : +value;
    return acc;
  }, Object.create(null));
}

console.log(simpleParse(s));

You could convert the string to JSON, then use JSON.parse, but I don't see the point of parsing it twice. If the structure gets more complex, you'll need a more complex parser.

Comments

1

A lot of people are suggesting using the JSON.parse function, however it is not a valid json format. So it would simply return SYNTAX ERROR: Unexpected token a in JSON

What else comes to mind is using the eval function, but then again it would not work as the second parameter (2) isn't valid key in an object.

That being said we have to come up with some form of a transform function You can use splits to divide the function into separate parameters, and then use replace to remove the unnecesery spaces/brackets

var str = "{ a: 1, 2: 10, c: 3 }";
Object.assign({}, ...str.split(",").map(param => {
    param = param.replace("{", "").replace("}", "").split(":")
        .map(a=>a.replace(" ", ""));
    let object = {};
    object[param[0]]=param[1];
    return object;
}))
//returns {'2': 10, a: 1, c: 3}

after that assigning first part before the ":" to a key and the other part to the value is pretty straight forward. I then combine the smaller objects with one parameter each into a bigger one with object.assign.

2 Comments

What about objects with variable depth?
@slider—the complexity of the parser need only be sufficient to deal with the data it's parsing. Given the OP's example, it only needs to be fairly simple.
-1

EDIT As mentioned below this is not valid JSON, so I like this puzzle :P My final solution:

var str = "{ a: 1, 2: 10, c: 3 }";
obj = str.replace(/[ {}]/g, "").split(",");
new_obj = {};
obj.forEach(function(element) {
    var t = element.split(':');
    new_obj[t[0]] = t[1];
});
console.log(new_obj);

This creates an array without making everything into a string.

3 Comments

Note that the string is not valid JSON.
I did actually tried that at first and it didn't work
That changes the numbers to strings.

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.