简体   繁体   中英

Python convert Json string values to int float boolean

Objective: I am coming from javascript background. I am try to parse a json. json.loads is supposed to convert stringfied values into their relevant type.

How can it be done with python 3? Purpose is eval all values with relevant type.

Scenerio: I am reading csv in python when reading csv, values are converted to strings I removed csv code becuase it was not relevant !!!

Code:

import json
x = '{ "name":"John", "age":30, "dev":"true", "trig":"1.0E-10", "res":"0.1"}'
y = json.loads(x)
print(y)

Current Output:

{
  "name": "John",
  "age": "30", 
  "dev": "true", 
  "trig": "1.0E-10", 
  "res": "0.1"
}

Expected output:

{
  "name": "John",
  "age": 30,       // int 
  "dev": true,     //  bool
  "trig": 1.0E-10, // real number
  "res": 0.1       // float
}

First you need to load your json from file

file = open('data.json', 'r')
content = file.read()
file.close()

Then we can go over each value and check whether we can convert it to int or float or if its either 'true' or 'false' , if so we update specific value of our dictionary.

import json

loaded_json = json.loads(content)

def is_type(x, t):
    try:
        t(x)
        return True
    except:
        return False

for k, v in loaded_json.items():
    if is_type(v, int):
        loaded_json[k] = int(v)
    elif is_type(v, float):
        loaded_json[k] = float(v)
    elif v == 'true':
        loaded_json[k] = True
    elif v == 'false':
        loaded_json[k] = False

for k, v in sorted(loaded_json.items()):
    print(k, v, '//', type(v))

Output:

age 30 // <class 'int'>
dev True // <class 'bool'>
name John // <class 'str'>
res 0.1 // <class 'float'>
trig 1e-10 // <class 'float'>

Your fundamental problem is that your json data contains strings, not values (eg "dev":"true" instead of "dev":true ). Parsing the string in javascript will hit the same problems you're seeing in Python:

(dev) go|c:\srv\tmp> node
> x = '{ "name":"John", "age":30, "dev":"true", "trig":"1.0E-10", "res":"0.1"}'
'{ "name":"John", "age":30, "dev":"true", "trig":"1.0E-10", "res":"0.1"}'
> JSON.parse(x)
{ name: 'John', age: 30, dev: 'true', trig: '1.0E-10', res: '0.1' }
> JSON.parse(x).dev
'true'
> typeof JSON.parse(x).dev
'string'

The real solution here is to fix whatever is creating such malformed json.

You can hack your way around it in Python by eg:

import ast, json

x = '{ "name":"John", "age":30, "dev":"true", "trig":"1.0E-10", "res":"0.1"}'

def evalfn(pairs):
    res = {}
    for key, val in pairs:
        if val in {'true','false'}:
            res[key] = val == 'true'
            continue
        try:
            res[key] = ast.literal_eval(val)
        except Exception as e:
            res[key] = val
    return res

y = json.loads(x, object_pairs_hook=evalfn)
print y

which will print

{u'trig': 1e-10, u'res': 0.1, u'age': 30, u'name': u'John', u'dev': True}

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