Home Safely turning a JSON string into an object
Reply: 0

Safely turning a JSON string into an object

user9315
1#
user9315 Published in September 20, 2018, 1:24 pm

Given a string of JSON data, how can you safely turn that string into a JavaScript object?

Obviously you can do this unsafely with something like...

var obj = eval("(" + json + ')');

...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.

share|improve this question
  • 67
    In most languages eval carries an additional risk. Eval leaves an open door to be exploited by hackers. HOWEVER, remember that all javascript runs on the client. EXPECT that it will be changed by hackers. They can EVAL anything they want, just by using the console. You must build your protection on the server side. – Beachhouse Feb 7 '13 at 17:34
  • 15
    Ok, now it is 2014 and you should never use eval in order to parse a JSON string because you would be exposing your code to "code injection". Use JSON.parse(yourString) instead. – Daniel Oct 22 '14 at 6:27
  • Is the JSON data a literal ? – shanechiu Sep 25 '17 at 10:02
  • @shanechiu: if you mean a scalar data type, yes it is. Is just a string with a key-value syntax in it. – 0zkr PM 2 days ago

25 Answers 25

active oldest votes
up vote 1735 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.463779 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO