This is my environment variable:
export DATA='{firstName: "OAMAR", lastName: "KANJI"}'
process.env.DATA
sees this as a string but doing something like JSON.parse(process.env.DATA)
does not work as the keys in the object are not strings. I.e something like JSON.parse('{"firstName": "OAMAR", "lastName": "KANJI"}')
would work but this is not the form of the environment variable.
Any ideas on how to convert the string to JSON?
This is my environment variable:
export DATA='{firstName: "OAMAR", lastName: "KANJI"}'
process.env.DATA
sees this as a string but doing something like JSON.parse(process.env.DATA)
does not work as the keys in the object are not strings. I.e something like JSON.parse('{"firstName": "OAMAR", "lastName": "KANJI"}')
would work but this is not the form of the environment variable.
Any ideas on how to convert the string to JSON?
Share Improve this question edited Jan 25, 2019 at 21:11 Oamar Kanji asked Jan 25, 2019 at 20:39 Oamar KanjiOamar Kanji 2,2247 gold badges28 silver badges47 bronze badges 4-
3
Strings in JSON have to be in double quotes, not single quotes, so
'OAMAR'
is wrong as well. – Barmar Commented Jan 25, 2019 at 20:41 -
1
Why not just make your environment variable valid JSON? The only thing built-in that will parse something like this is
eval()
, but that's dangerous. – Barmar Commented Jan 25, 2019 at 20:49 - @Barmar thank you, i will edit that in my question and make a personal note of that. As for entering valid json, it returns an error when I source my .env file – Oamar Kanji Commented Jan 25, 2019 at 21:09
-
export DATA='{"firstName": "OAMAR", "lastName": "KANJI"}'
should not cause an error. – Barmar Commented Jan 25, 2019 at 21:13
2 Answers
Reset to default 3export DATA='{"firstName": "OAMAR", "lastName": "KANJI"}'
change your format then used like
var foo =JSON.parse(DATA);
You can try converting your string to a valid JSON String then change it back to JSON
const Data ='{firstName: "OAMAR", lastName: "KANJI"}';
const output = JSON.parse(JSON.stringify(Data));
console.log(output);