parsing JSON string into numeric

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

parsing JSON string into numeric

Post by devnull » Wed Mar 22, 2017 12:51 pm

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 ?

SpotlightKid
Posts: 463
Joined: Wed Apr 08, 2015 5:19 am

Re: parsing JSON string into numeric

Post by SpotlightKid » Wed Mar 22, 2017 8:00 pm

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')

User avatar
devnull
Posts: 473
Joined: Sat Jan 07, 2017 1:52 am
Location: Singapore / Cornwall
Contact:

Re: parsing JSON string into numeric

Post by devnull » Thu Mar 23, 2017 3:06 am

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.

Post Reply