var jsonString = '{"user":{"id":1,"name":{"first":"太郎","last":"山田"},"age":30,"email":"taro.yamada@example.com","address":{"street":"1-2-3","city":"東京","prefecture":"東京都","postalCode":"100-0001"},"phoneNumbers":[{"type":"mobile","number":"090-1234-5678"},{"type":"home","number":"03-1234-5678"}],"hobbies":[{"name":"サッカー","level":"中級"},{"name":"読書","genres":["フィクション","ノンフィクション","ミステリー"]},{"name":"料理","skills":{"cuisine":["和食","イタリアン"],"level":"上級"}}],"preferences":{"language":"日本語","notifications":{"email":true,"sms":false,"push":true}}}}'
var jsonString2 = '({"user":{"id":1,"name":{"first":"太郎","last":"山田"},"age":30,"email":"taro.yamada@example.com","address":{"street":"1-2-3","city":"東京","prefecture":"東京都","postalCode":"100-0001"},"phoneNumbers":[{"type":"mobile","number":"090-1234-5678"},{"type":"home","number":"03-1234-5678"}],"hobbies":[{"name":"サッカー","level":"中級"},{"name":"読書","genres":["フィクション","ノンフィクション","ミステリー"]},{"name":"料理","skills":{"cuisine":["和食","イタリアン"],"level":"上級"}}],"preferences":{"language":"日本語","notifications":{"email":true,"sms":false,"push":true}}}})'
var dummy = JSON.parse(jsonString);
var dummy = eval(jsonString2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JSON.parse() | |
eval() |
Test name | Executions per second |
---|---|
JSON.parse() | 243761.8 Ops/sec |
eval() | 22918.9 Ops/sec |
The benchmark presented compares two different methods for parsing a JSON-like string in JavaScript: JSON.parse()
and eval()
.
JSON.parse()
var dummy = JSON.parse(jsonString);
JSON.parse()
is inherently safer as it does not execute any JavaScript code contained in the string. This makes it less vulnerable to code injection attacks.eval()
.eval()
var dummy = eval(jsonString2);
eval()
executes the string as JavaScript code, it can handle any JavaScript expression, not just valid JSON.eval()
poses significant security risks as it can execute potentially harmful code if the input string is derived from an untrusted source.JSON.parse()
for parsing JSON as it has to invoke the JavaScript interpreter and execute the code, which adds overhead.JSON.stringify()
) and parsing (JSON.parse()
).JSON.parse()
for parsing JSON due to its safety, performance, and clarity. eval()
might only be considered in very specific contexts where dynamic execution of JavaScript is required, and the input can be trusted.lodash
can be used, though they typically do not replace JSON.parse()
. lodash
can handle deep cloning, merging, and other data transformations which extend beyond simple parsing.In summary, for typical JSON parsing tasks, JSON.parse()
is the recommended approach due to its security, performance, and consistency, while eval()
should be avoided unless absolutely necessary and only with trusted input.