简体   繁体   中英

JavaScript JSON reviver in Python

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

import json

def parse_value(value):
    if(isinstance(value, str)):
        try:
            return parse_value(json.loads(value))
        except:
            pass
        semi_values = value.split(';')
        if(len(semi_values) > 1):
            return list(map(parse_value, semi_values))
        comma_values = value.split(',')
        if(len(comma_values) > 1):
            return list(map(parse_value, comma_values))
        if(value.replace('.','',1).isdigit()):
            return int(value)
    if(isinstance(value, dict)):
        return {k: parse_value(v) for k, v in value.items()}
    if(isinstance(value, list)):
        return list(map(parse_value, value))
    return value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM