Home > other >  python parsing strange JSON data
python parsing strange JSON data

Time:04-28

How should I parse (with Python3) data in this "unusual" format? As you can see inside the "variables" dictionary the data that is in capitals has no label, it is provided as a literal. Therefore when I loop over the entries inside "variables" all I get is the strings in capitals, nothing else. I need, obviously, to get the capitals plus the value inside it.

    {
    "variables": {
    "ABSENCE_OSL_PROD": {
      "value": "REZWWnBTejN5Ng=="
    },
    "ACTION_OSL_INT": {
      "value": "S0RXSVNTbmFhNw=="
    },
    "ACTION_OSL_PROD": {
      "value": "RUJCaDJGnmFnUg=="
    },
    "API_STORE_OSL_INT": {
      "value": "U3lxaVhogWtIcg=="
    }
  },
  "id": 4,
  "type": "Vsts"
}

CodePudding user response:

To load the variables inside variables in the local variable space:

data =    {
    "variables": {
    "ABSENCE_OSL_PROD": {
      "value": "REZWWnBTejN5Ng=="
    },
    "ACTION_OSL_INT": {
      "value": "S0RXSVNTbmFhNw=="
    },
    "ACTION_OSL_PROD": {
      "value": "RUJCaDJGnmFnUg=="
    },
    "API_STORE_OSL_INT": {
      "value": "U3lxaVhogWtIcg=="
    }
  },
  "id": 4,
  "type": "Vsts"
}

for variable_name, variable_content in data['variables'].items():
    locals()[variable_name] = variable_content['value']

print(ABSENCE_OSL_PROD)
# prints "REZWWnBTejN5Ng=="

CodePudding user response:

With dict comprehension you can get a time efficient manner:

ugly = {
    "variables": {
    "ABSENCE_OSL_PROD": {
      "value": "REZWWnBTejN5Ng=="
    },
    "ACTION_OSL_INT": {
      "value": "S0RXSVNTbmFhNw=="
    },
    "ACTION_OSL_PROD": {
      "value": "RUJCaDJGnmFnUg=="
    },
    "API_STORE_OSL_INT": {
      "value": "U3lxaVhogWtIcg=="
    }
  },
  "id": 4,
  "type": "Vsts"
}

proper = {elt: ugly["variables"][elt]["value"] for elt in ugly["variables"]}

print(proper)

returns

{'ABSENCE_OSL_PROD': 'REZWWnBTejN5Ng==', 'ACTION_OSL_INT': 'S0RXSVNTbmFhNw==', 'ACTION_OSL_PROD': 'RUJCaDJGnmFnUg==', 'API_STORE_OSL_INT': 'U3lxaVhogWtIcg=='}```
  • Related