user11646543
user11646543

Reputation: 49

How to convert string of integers into integer?

import json
class Decoder(json.JSONDecoder):
     def decode(self, s):
         result = super(Decoder, self).decode(s)
        return self._decode(result)
     def _decode(self, o):
         if isinstance(o, str) or isinstance(o, unicode):
             try:
                 return int(o)
             except ValueError:
                 try:
                    return float(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
With open('data.json') as f:
data = json.loads(f,cls=Decoder)


**Error code is:**
    Traceback (most recent call last):
  File "\\Program:(c)\Folder\sample\pyhton\sample.py", line 29, in <module>
    data = json.loads(f,cls=Decoder)
  File "C:\Program Files (x86)\Python36-32\lib\json\__init__.py", line 348, in loads
    'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'TextIOWrapper'

Python Version:3.6.4

How to resolve this error?

I am trying to convert the string integers into integers, using class.

Regards, Sriram

Upvotes: 0

Views: 83

Answers (1)

SitiSchu
SitiSchu

Reputation: 1417

json.loads is for loading json strings

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table. (https://docs.python.org/3/library/json.html#json.loads)

For loading json files you want data = json.load(f,cls=Decoder) (note the missing s).

Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table. (https://docs.python.org/3/library/json.html#json.load)

In your case you don't even need the custom Decoder since the json module will automatically convert floats and integers for you:

>>> import json
>>> json.loads('{"a": 0.254}')
{'a': 0.254}

so doing this should suffice:

data = json.load(f)

Upvotes: 1

Related Questions