I'm having problem translating my JavaScript snippet to Python.
The JavaScript code looks like this:
const reviver = (_key, value) => {
try {
return JSON.parse(value, reviver);
} catch {
if(typeof value === 'string') {
const semiValues = value.split(';');
if(semiValues.length > 1) {
return stringToObject(JSON.stringify(semiValues));
}
const commaValues = value.split(',');
if(commaValues.length > 1) {
return stringToObject(JSON.stringify(commaValues));
}
}
const int = Number(value);
if(value.length && !isNaN(int)) {
return int;
}
return value;
}
};
const stringToObject = (str) => {
const formatted = str.replace(/"{/g, '{').replace(/}"/g, '}').replace(/"\[/g, '[').replace(/\]"/g, ']').replace(/\\"/g, '"');
return JSON.parse(formatted, reviver);
};
The goal of the function is that:
- String values that are numbers are parsed
- String values that are json are parsed using these rules
- String values like
"499,504;554,634"
should be parsed to[(499, 504), (554, 634)]
I have tried using the JSONDecoder.
import json
def object_hook(value):
try:
return json.loads(value)
except:
if(isinstance(value, str)):
semiValues = value.split(';')
if(len(semiValues) > 1):
return parse_response(json.dumps(semiValues))
commaValues = value.split(',')
if(commaValues.length > 1):
return parse_response(json.dumps(commaValues))
try:
return float(value)
except ValueError:
return value
def parse_response(data: str):
formatted = data.replace("\"{", "{").replace("}\"", '}').replace("\"[", '[').replace("]\"", ']').replace("\\\"", "\"")
return json.load(formatted, object_hook=object_hook)
I solved my issue by iterating through the values and parse them accordingly