Change Key in JSON, when DASH “-” is present in key – nodeJS or JavaScript

Tags: , ,

I have no idea how to rename key that has dash in it. for example

obj.Fast-Italian = obj.Fast-Car1;

While below code works for keys that doesn’t contain dash “-“:

var json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"","image":"some_image_url","name":"Name 1"}]';

var obj = JSON.parse(json)[0]; = obj._id;
delete obj._id;
json = JSON.stringify([obj]);
fs.writeFileSync('output1.json', json);

I can’t use above for this JSON:

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"}]'
    // what I need to go here is change Fast-Car1 Fast-Italian, Fast-Car2 = Fast-German, Fast-Car3 = Fast-Japanese

Problem is I don’t know how to make this work:

obj.Fast-Italian = obj.Fast-Car1;

due to dash “-” in Key name.

    //so final JSON would look like this:
    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"}]'
    // JSON has big amount of those, so I will loop anyway, but I have no idea how to 

I tried this :

var obj = JSON.parse(json)[0];
obj.[Fast-Italian] = obj.['Fast-Car1'];
delete obj._id;

but then got error:

// = obj.['Fast-Car1'];
// SyntaxError: Unexpected token '['

Extra note: JSON comes from Excel where each column has Fast-[Something] (in case you were wondering why I have JSON keys with dash “-“)


You were on the right track with:

var obj = JSON.parse(json)[0];
obj.[Fast-Italian] = obj.['Fast-Car1'];
delete obj._id;

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

var obj = JSON.parse(json)[0];
obj['Fast-Italian'] = obj['Fast-Car1'];
delete obj['Fast-Car1'];

Source: stackoverflow