Regex: how to deal with brackets and back slashes? Example: make "[{\ into [{

Viewed 74

I am converting a csv file into JSON, and the converter adds " at the beginning of lines, and also adds a \ to quotes.

So, if my CSV file has an array like

"items": [{"name":"item 1"...

the resulting JSON from the converter is:

"items": "[{\"name\":\"item 1\"...

I need the JSON to look like the original CSV entry.

So, how do I change "[{ to [{ ?

Note: I can't just remove quotes everywhere, as they are correct in certain spots. So I need to just remove quotes when they are followed by these specific characters, so only remove "[{

And how do I remove the \ everywhere they appear?

EDIT Some of the comments and answers have mentioned maybe there is a better way to convert the CSV into a JSON file. In my case, I have data in excel that I need to ultimately be readable by a Lambda function, so I expect I need a way to convert excel to JSON. I have posted a separate question asking for assistance on that topic here .

2 Answers

First of all you should try to generate the correct json format, so that you don't have to go through this issue at all.

However if you have no control over the output of the json data that you're getting, you can simply remove the \" parts by using this regexp:

your_json_var.toString().replace(/\"/g,'');

Where your_json_var contains the returned data.

your_json_var = '"items": "[{\"name\":\"item 1\"...';

var new_var = your_json_var.toString().replace(/\"/g,'');

console.log(new_var);

You could do this Let stringJson=JSON.stringify(myjson) Let clearJson = JSON.parse(stringJson.replace(/\"[{/g, '[{').replace(/\/g,'')

Related