1

Im a receiving a string of an array containing objects via http request. I parse it with eval().

So I am clearly expecting an array obj after parsing. How do i secure this eval() procedure, besides of if (Array.isArray(parsedObj)) ...

Is there even a better way than eval()?

This is part of the string (note that its not a JSON):

    [
        ["2018-06-06", "2018-06-07", "2018-06-08", "2018-06-09", "2018-06-10", "2018-06-11", "2018-06-12", "2018-06-13", "2018-06-14", "2018-06-15", "2018-06-16"], 
        {
            "2018-06-10": {
                checkFirstOrLastOfMonth: 0,
                day: "10",
                dayOfWeek: "SONNTAG",
                formatedDate: "10 Jun 2018",
                monthNo: "06",
                shortMonthName: "Jun",
                weekOfYear: 24,
                year: "2018"
            },
            "2018-06-11": {
                checkFirstOrLastOfMonth: 0,
                day: "11",
                dayOfWeek: "MONTAG",
                formatedDate: "11 Jun 2018",
                monthNo: "06",
                shortMonthName: "Jun",
                weekOfYear: 24,
                year: "2018"
            },
            "2018-06-09": {
                checkFirstOrLastOfMonth: 0,
                day: "09",
                dayOfWeek: "SAMSTAG",
                formatedDate: "09 Jun 2018",
                monthNo: "06",
                shortMonthName: "Jun",
                weekOfYear: 23,
                year: "2018"
            },
    ...
4
  • 3
    Never use eval. Write your own parser then. Commented Jun 6, 2018 at 12:13
  • 6
    Why don't you make it valid JSON? Fix the HTTP API. Commented Jun 6, 2018 at 12:14
  • 2
    Checking the type of the outermost expression after parsing does not make anything more secure. Commented Jun 6, 2018 at 12:15
  • @Beri: fixing the API is not in my hand, unfort ... Commented Jun 6, 2018 at 12:19

1 Answer 1

2

Instead of eval() use https://www.npmjs.com/package/json5

to parse a relaxed JSON like that string into a js obj/arr

npm install json5 --save

_

const JSON5 = require('json5');

let obj = JSON5.parse(obj_str);
Sign up to request clarification or add additional context in comments.

1 Comment

JSON5 provides extended set of rules that isn't possible in JSON. E.g. a number can be NaN. Is it desirable? There are multiple packages that parse JSON in more loose manner but don't do any enhancements, like npmjs.com/package/loose-json

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.