简体   繁体   中英

How to exclude a integer that is a string in a json using isinstance python

I have a json that has all values of strings. I have a decoder that takes all the strings and decodes them into the integers, but there is one value that is showing as "01" that I would like to keep as a string. Is it possible to exclude this in the decoder for it to stay as a string and not parse as a integer.

My JSON is below:

{"Data NC": "0", "Date": "10/10/2018", "Open Report": "142", "Date NC1": "40", "New Data": "0", "Some Report": "71", "New Data1": "01", "Date": "10/06/2021 00:00:00 AM"}

I've already tried using: and not isinstance("New Data1", "01) condition, but I got no luck. Is there a way to do this. Code is below:

class Decoder(json.JSONDecoder):
    def decode(self, s):
        result = super().decode(s)  # result = super(Decoder, self).decode(s) for Python 2.x
        return self._decode(result)

    def _decode(self, o):
        if isinstance(o, str):
            try:
                return int(o)
            except ValueError:
                return o
        elif isinstance(o, dict):
            return {k: self._decode(v) for k, v in o.items()}
        elif isinstance(o, list):
            return [self._decode(v) for v in o]
        else:
            return o

Using json.loads to load the decoder above:

json_doc = json.loads(doc, cls=Decoder)

Any help would be appreciated.

You can put this code in your try: except -block:

result = int(o)
if str(result) == o:
    return result
else:
    return o

it converts the converted integer back to string and compares it with the original. If they are equal all is fine, if not it returns the string (because the integer has leading 0s and should not be converted). Single 0s were converted to integers. The output will be:

{
  'Data NC': 0,
  'Date': '10/06/2021 00:00:00 AM',
  'Open Report': 142,
  'Date NC1': 40,
  'New Data': 0,
  'Some Report': 71,
  'New Data1': '01'
}

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