簡體   English   中英

Python將Json字符串值轉換為int float boolean

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

目標:我來自javascript背景。 我嘗試解析json。 json.loads應該將字符串化的值轉換為它們的相關類型。

如何用python 3完成? 目的是評估所有具有相關類型的值。

Scenerio:讀取csv時,我正在python中讀取csv,將值轉換為字符串,我刪除了csv代碼,因為它不相關!

碼:

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

電流輸出:

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

預期產量:

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

首先,您需要從文件加載json

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

然后,我們可以遍歷每個值,並檢查是否可以將其轉換為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))

輸出:

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

您的根本問題是您的json數據包含字符串,而不包含值(例如"dev":"true"而不是"dev":true )。 在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'

真正的解決方案是修復導致這種格式錯誤的json的所有內容。

您可以通過以下方式在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

將打印

{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