motdotla/dotenv

Support parsing escaped JSON values

noahw3 opened this issue · 2 comments

noahw3 commented

Currently JSON values that have been stringified are not handled well. They are not stripped of the escaping, and thus fail to parse when attempting to interpret them as JSON.

Example file:

CONFIG_JSON="{\"fielda\":\"testvalue=\",\"fieldb\":false,\"fieldc\":null,\"fieldd\":{\"nested\":\"true\"}}"

Expected parsed output:

{
  CONFIG_JSON: '{"fielda":"testvalue=","fieldb":false,"fieldc":null,"fieldd":{"nested":"true"}}',
}

Actual parsed output:

{
  CONFIG_JSON: '{\\"fielda\\":\\"testvalue=\\",\\"fieldb\\":false,\\"fieldc\\":null,\\"fieldd\\":{\\"nested\\":\\"true\\"}}',
}

Libraries like ini will sometimes write escaped JSON depending on the input. In the above example, including the = in the testvalue value would cause it to do so.

It's not very elegant, but the way that ini handles this is attempting to parse the value as JSON if it looks like JSON, and just ignoring any errors.

Emmo00 commented

Hey @motdotla , what are your thoughts on this?

Can I attempt a fix for this?

using single ' quotes or backticks .

CONFIG_JSON='{"fielda":"testvalue=","fieldb":false,"fieldc":null,"fieldd":{"nested":"true"}}'

working example here: https://github.com/dotenv-org/examples/blob/master/usage/dotenv-nodejs-json-escaped/.env