最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert environment variable to JSON object? - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3
export 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);

发布评论

评论列表(0)

  1. 暂无评论