[sonic-config-engine][portconfig] Do not parse JSON as Python AST (#10224)

#### Why I did it
To fix https://github.com/Azure/sonic-buildimage/issues/9643

#### How I did it
Instead of ast.literal_eval added python2 compat code for json strings unicode -> str convertion.

We need python2 compatibility since py2 sonic config engine (buster/sonic_config_engine-1.0-py2-none-any.whl target) is still included into the build (ENABLE_PY2_MODULES flag is set for buster). Once we abandon buster and python2, this compat and ast.literal_eval could be cleaned up all through the code base.

#### How to verify it
run steps from the linked issue
This commit is contained in:
Volodymyr Boiko 2022-03-21 21:43:43 +02:00 committed by Qi Luo
parent 3402094fd0
commit d2195aa722
2 changed files with 27 additions and 6 deletions

View File

@ -45,16 +45,25 @@ BRKOUT_PATTERN = r'(\d{1,3})x(\d{1,3}G)(\[\d{1,3}G\])?(\((\d{1,3})\))?'
# #
# Helper Functions # Helper Functions
# #
# For python2 compatibility
def py2JsonStrHook(j):
if isinstance(j, unicode):
return j.encode('utf-8', 'backslashreplace')
if isinstance(j, list):
return [py2JsonStrHook(item) for item in j]
if isinstance(j, dict):
return {py2JsonStrHook(key): py2JsonStrHook(value)
for key, value in j.iteritems()}
return j
def readJson(filename): def readJson(filename):
# Read 'platform.json' or 'hwsku.json' file # Read 'platform.json' or 'hwsku.json' file
try: try:
with open(filename) as fp: with open(filename) as fp:
try: if sys.version_info.major == 2:
data = json.load(fp) return json.load(fp, object_hook=py2JsonStrHook)
except json.JSONDecodeError: return json.load(fp)
print("Json file does not exist")
data_dict = ast.literal_eval(json.dumps(data))
return data_dict
except Exception as e: except Exception as e:
print("error occurred while parsing json: {}".format(sys.exc_info()[1])) print("error occurred while parsing json: {}".format(sys.exc_info()[1]))
return None return None

View File

@ -1,4 +1,16 @@
{ {
"chassis": {
"psus": [
{
"name": "PSU 1",
"temperature": false
},
{
"name": "PSU 2",
"temperature": false
}
]
},
"interfaces": { "interfaces": {
"Ethernet0": { "Ethernet0": {
"index": "1,1,1,1", "index": "1,1,1,1",