Summary:
I have no idea how to rename key that has dash in it. for example
JavaScript
x
2
1
obj.Fast-Italian = obj.Fast-Car1;
2
While below code works for keys that doesn’t contain dash “-“:
JavaScript
1
9
1
var json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"user1@gmail.com","image":"some_image_url","name":"Name 1"}]';
2
3
var obj = JSON.parse(json)[0];
4
obj.id = obj._id;
5
delete obj._id;
6
7
json = JSON.stringify([obj]);
8
fs.writeFileSync('output1.json', json);
9
I can’t use above for this JSON:
JavaScript
1
3
1
var json = '[{"Fast-Car1":"Ferrari F40 Cabrio","Fast-Car2":"Audi R8 Black Edition","Fast-Car3":"Nissan GTR Blue"},{"Fast-Car1":"Lambo Diablo Fire Colors","Fast-Car2":"Skoda RS 4 doors","Fast-Car3":"Honda NSX red paint"}]'
2
// what I need to go here is change Fast-Car1 Fast-Italian, Fast-Car2 = Fast-German, Fast-Car3 = Fast-Japanese
3
Problem is I don’t know how to make this work:
JavaScript
1
2
1
obj.Fast-Italian = obj.Fast-Car1;
2
due to dash “-” in Key name.
JavaScript
1
5
1
//so final JSON would look like this:
2
var json = '[{"Fast-Italian":"Ferrari F40 Cabrio"},{"Fast-German":"Audi R8 Black Edition"},{"Fast-Japanese":"Nissan GTR Blue"},,{"Fast-Italian":"Lambo Diablo Fire Colors","Fast-German":"VW Golf RS silver","Fast-Japanese":"Honda NSX red paint"}]'
3
// JSON has big amount of those, so I will loop anyway, but I have no idea how to
4
5
I tried this :
JavaScript
1
4
1
var obj = JSON.parse(json)[0];
2
obj.[Fast-Italian] = obj.['Fast-Car1'];
3
delete obj._id;
4
but then got error:
JavaScript
1
3
1
// obj.id = obj.['Fast-Car1'];
2
// SyntaxError: Unexpected token '['
3
Extra note: JSON comes from Excel where each column has Fast-[Something] (in case you were wondering why I have JSON keys with dash “-“)
Advertisement
Answer
You were on the right track with:
JavaScript
1
4
1
var obj = JSON.parse(json)[0];
2
obj.[Fast-Italian] = obj.['Fast-Car1'];
3
delete obj._id;
4
There are 2 problems…
One, you dont mix and match dot notation and bracket notation. So dont do obj.[keyname] you just do obj[keyname].
Two, Fast-Italian isn’t a declared variable name from what I can see… its just supposed to be a string key name.. so you need to enclose it with quotes
JavaScript
1
4
1
var obj = JSON.parse(json)[0];
2
obj['Fast-Italian'] = obj['Fast-Car1'];
3
delete obj['Fast-Car1'];
4