2

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?

asked Jan 25, 2019 at 20:39
4
  • 3
    Strings in JSON have to be in double quotes, not single quotes, so 'OAMAR' is wrong as well. 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. 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 Commented Jan 25, 2019 at 21:09
  • export DATA='{"firstName": "OAMAR", "lastName": "KANJI"}' should not cause an error. Commented Jan 25, 2019 at 21:13

2 Answers 2

3
export DATA='{"firstName": "OAMAR", "lastName": "KANJI"}'

change your format then used like

var foo =JSON.parse(DATA);
answered Jan 25, 2019 at 21:15
Sign up to request clarification or add additional context in comments.

Comments

2

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);

answered Jan 25, 2019 at 21:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.