user1249261
user1249261

Reputation: 1

Unable to parse string of json which is passed as an argument from other node program

* Update :* i had enclosed the changeSet in double quotes too inspite of that i still get the same error

This is what am trying to achieve

am calling script function which checks the newly modified files in my project and passes those as a String in the form of JSON to another node program as an argument

where i can use that Json to perform the tasks

however am unable to parse that string into JSON

so the JSON in question is this {"changeSet":[{"time":"2019-06-2810:22:57","fileName":"src/MainHandler.jsx"},{"time":"2019-06-2013:08:45","fileName":"resSet.json"}]}

node findChanges changesJson

in the function where this is being passed as an argument

i tried all sorts of things

like parsing it through JSON.parse method

to trimming the argument and then parsing it ,no matter what i do , i keep getting syntax Error

i have also tried enclosing the changeSet attribute in double Quotes still i keep getting the same error

let cs = process.argv[2];

let b = JSON.parse(cs); //here I get the parsing error

console.log(b.changeSet);

//i have also tried stringifying it first and parsing it 
//trimming it --->stringifying it ---->parsing it
undefined:1
{changeSet
 ^

SyntaxError: Unexpected token c in JSON at position 1
    at JSON.parse (<anonymous>)

Upvotes: 0

Views: 132

Answers (3)

Shivani Sonagara
Shivani Sonagara

Reputation: 1307

var result =  {"changeSet":[{"time":"2019-06-2810:22:57","fileName":"src/MainHandler.jsx"},{"time":"2019-06-2013:08:45","fileName":"resSet.json"}]};

console.log(result.changeSet)

Problem is in your input. ChangeSet should be in the quotes.

You may try to give input as below format:

{"changeSet":[{"time":"2019-06-2810:22:57","fileName":"src/MainHandler.jsx"},{"time":"2019-06-2013:08:45","fileName":"resSet.json"}]}

Before started working, always check on it Onlint JSON parser

Upvotes: 1

S. Stumm
S. Stumm

Reputation: 290

you miss quotes around your json-string.

Upvotes: 1

Terry Lennox
Terry Lennox

Reputation: 30705

The JSON in question is invalid, you need to add quotes around changeSet, e.g.

{
    "changeSet": [
        {
            "time": "2019-06-2810:22:57",
            "fileName": "src/MainHandler.jsx"
        },
        {
            "time": "2019-06-2013:08:45",
            "fileName": "resSet.json"
        }
    ]
}

Upvotes: 1

Related Questions