Recently I found a piece of code that takes input from the url. The input then get's saved into a javascript object:


var x = {"foo": "bar"};

While the value doesn't allow opening and closing brackets the key does. Single and double quotes are properly handled in the key and are completely removed in the value.

Is this a potential security risk or is it safe to implement something like this?

Is it safe to let the user name an object key in JavaScript?

  • 1
    I guess it mostly depends on „properly handled“, can you show the code? – eckes Apr 18 '19 at 11:31
  • @eckes I tried to find the code that is responible for handling but all I could find out is that there are multiple independent scripts that handle setting the variable, modifying the variable and checking for single and double quotes. The quotes are handled as follows: " converts to \" and \" converts to \\\". Hope that helps a bit. – BloodViolet Apr 18 '19 at 12:06
  • I disagree with the close votes. I don't think it's too broad to give a sensible answer. – Arminius Apr 18 '19 at 16:48

It is somewhat dangerous and not always correct to use user defined properties on Objects. It is typically recommended to use a Map object (in recent browsers) or some of the custom libraries to emulate it.

Some pitfalls are described here: http://2ality.com/2012/01/objects-as-maps.html

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.