JavaScript Object vs Map - how to handle special keys?

In Java, I believe one should take a string and use it as a key in LinkedHashMap

. I can even translate it to JSON and back with no problem.

Now I am using Node.JS / JavaScript and there is a special case not being handled.

var makesSense = '{"__proto__":"foo","toString":"bar"}'
var noSense = JSON.stringify(JSON.parse('{"__proto__":"foo","toString":"bar"}'))
console.log(noSense) // outputs {"toString":"bar"}

      

What is the recommended way to handle __proto__

and other things like that. This would seem to toString

cause no problems, but assumed that I needed serial processing of untrusted data. What's the recommended solution?

  • Prepare an extra character before each key? If so, what character makes sense? I know it can't be an underscore, but what about a space?
  • Use a module that handles this for me? I would like it to be convenient and without unnecessary features. (some features would be nice though)
  • Something else? Is there a solution that is compatible with JSON.parse

    ?

Why does it matter? Surely no one actually picks up by __proto__

accident. But what if they do it on purpose. They are learning, I use JavaScript, so what? - No problem except in the following situation:

  • The software has an array of strings. So, one of these lines says __proto__

    because someone was shaking trying to break my software.
  • The software creates a map using these strings for the key and populates the map with some good data.
  • The software then walks through the array of strings and gathers information from the card. Map returns something null, and then boom: null pointer exception.
  • The software does not work now. This could qualify as something like a denial of service.

I know this situation is completely different, but I don't like it. I can't remember all the quirks of the programming language I use, so given enough time, I must write code like this.

I am proud to create code that cannot be tampered with. So, I am trying to remove these stains from my software.

Yes, they are super minor, but at least it's worth asking StackOverflow to see if people have a better answer than I know. I've learned a lot.

+3


source to share


1 answer


Prepare an extra character before each key? If so, what character makes sense? I know it can't be an underscore, so what about a space?



I use x

, but that's arbitrary. As long as you use something that is unlikely to form a special property name, like (on some engines) __proto__

or toString

, or valueOf

(and I don't know of any special property names starting with x

), you're fine.

0


source







All Articles