0

I am trying to read an environment variable from a JSON object that looks like this:

{
  "staging_env_json": {},
  "running_env_json": {},
  "system_env_json": {
    "EN_VAR_NAME": {
      "mysql": [
        {
          "name": "name-here",
          "label": "label-here",
          "tags": [
            "mysql",
            "relational"
          ],
          "plan": "",
          "credentials": {
            "hostname": "host",
            "port": "port",
            "name": "name-here",
            "username": "username",
            "password": "password",
          }
        }
      ]
    }
  }
}

Using C# how would I access the username and password? I have tried this....

envVariable = Environment.GetEnvironmentVariable("EN_VAR_NAME");      
var obj = JObject.Parse(envVariable);
var hostname = (string)obj["mysql"]["credentials"]["username"];

But this isn't getting me where.. can anyone please point me in the right direction?

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
samcooper11
  • 265
  • 2
  • 10
  • 20

2 Answers2

1

You can parse it as dynamic:

dynamic result = JsonConvert.DeserializeObject<dynamic>(input);
Console.WriteLine(result.system_env_json.EN_VAR_NAME.mysql[0].credentials.username);
Richard
  • 29,854
  • 11
  • 77
  • 120
1
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(envVariable);
var userName = ((dynamic)obj).system_env_json.EN_VAR_NAME.mysql[0].credentials.username
joordan831
  • 720
  • 5
  • 6
  • Sorry if this is a stupid question - but where there is 'mysql' in the JSON object this is actually being returned as p-mysql but i cannot build using this: var hostname = obj.system_env_json.EN_VAR_NAME.p-mysql[0].credentials.username; as it doesn't like the p- any ideas on how i can resolve this? – samcooper11 Jan 15 '16 at 11:24
  • 1
    This should work. ((dynamic)obj).system_env_json.EN_VAR_NAME["p-mysql"][0].credentials.username – joordan831 Jan 15 '16 at 18:21