Page 1 of 1

parsing JSON string into numeric

Posted: Wed Mar 22, 2017 12:51 pm
by devnull
I have JSON data that is posted via javascript from a web page, every field is sent as a string irregardless of whether it is a string, number or boolean value, I cannot change that.

So I need to convert the data where a value looks like a number into a numeric value:

Code: Select all

data = {
  'a':"1",
  'b':True,
  'c':11.22,
  'd':"22.11",
  'e':"Hello World 1234"
}

for key in data:
  try:
    if(not type(data[key])==bool):
      data[key] = float(data[key])
      if(data[key]%1==0):
        data[key] = int(data[key])
  except:
    continue

print(data)
> {'d': 22.11, 'e': 'Hello World 1234', 'c': 11.22, 'a': 1, 'b': True}
As the actual data might be quite large is this the most efficient method ?

Re: parsing JSON string into numeric

Posted: Wed Mar 22, 2017 8:00 pm
by SpotlightKid
I could convert string values to float only a on-demand basis, e.g. when you're actually using them:

Code: Select all

get_float = lambda d, k: float(d.get(k, 0))
f = get_float(data, 'c')
or, a little bit fancier:

Code: Select all

class DictWrapper(dict):
    def get_float(self, key, default=0):
        val = self.get(key, default)
        try:
            return float(val)
        except:
            return val

data = DictWrapper(data)
f = data.get_float('c')

Re: parsing JSON string into numeric

Posted: Thu Mar 23, 2017 3:06 am
by devnull
Thanks, but what I forgot to mention is that I need to first save this data to a JSON file and later read and process it.

I would prefer that the saved json data uses numeric, boolean and string values rather than all strings to avoid having to repeatedly parse the float, integer in different areas of the code that read this file.