简体   繁体   English

Python将Json字符串值转换为int float boolean

[英]Python convert Json string values to int float boolean

Objective: I am coming from javascript background. 目标:我来自javascript背景。 I am try to parse a json. 我尝试解析json。 json.loads is supposed to convert stringfied values into their relevant type. json.loads应该将字符串化的值转换为它们的相关类型。

How can it be done with python 3? 如何用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 !!! Scenerio:读取csv时,我正在python中读取csv,将值转换为字符串,我删除了csv代码,因为它不相关!

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 首先,您需要从文件加载json

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. 然后,我们可以遍历每个值,并检查是否可以将其转换为intfloat或者是否将其转换为'true''false' ,如果是这样,我们将更新字典的特定值。

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 ). 您的根本问题是您的json数据包含字符串,而不包含值(例如"dev":"true"而不是"dev":true )。 Parsing the string in javascript will hit the same problems you're seeing in Python: 在javascript中解析字符串会遇到与在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. 真正的解决方案是修复导致这种格式错误的json的所有内容。

You can hack your way around it in Python by eg: 您可以通过以下方式在Python中破解它:

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM