无法使用json.loads将字符串加载到对象中

时间:2019-01-16 16:17:30

标签: python json oop

我正在尝试将字符串加载到python对象中。我得到以下错误: 这是错误的:预期值:第15行第15列(字符351) {'allData':无}

当我将cprob的值更改为以下代码时,没有问题:

    "cprob": {
        "T": 1,
        "A": 2,
        "C": 3
        }

test.txt中的数据:

[{
        "V": ["Offer", "Interview", "Grades", "Admission", "Experience"],
    "E": [["Grades", "Interview"],
        ["Experience", "Interview"],
        ["Grades", "Admission"],
        ["Interview", "Offer"]],
    "Vdata": {
        "Offer": {
            "ord": 4,
            "numoutcomes": 2,
            "vals": ["0", "1"],
            "parents": ["Interview"],
            "children": 0,
            "cprob": {
                "['0']": [.9, .1],
                "['1']": [.4, .6],
                "['2']": [.01, .99]
                }
            }
        }
}]

代码:

import json
class JsonData: 

    def __init__(self, path):
        self.allData = None 

    def dictload(self, path):
        f = open(path, 'r')
        ftext = f.read() 
        print(ftext)
        try: 
            self.allData = json.loads(ftext)
        except Exception as e:
            print('This is error : ', e)

path = "test.txt"

jsonData = JsonData(path)
jsonData.dictload(path)
print(vars(jsonData))

2 个答案:

答案 0 :(得分:4)

似乎python的json模块无法将public static string ReverseString(string s) { var toReturn = new StringBuilder(); for (var i = s.Length - 1; i >= 0; i--) { toReturn.Append(s[i]); } return toReturn.ToString(); } 理解为.1。如果将0.1添加到句点之前,它将起作用。

答案 1 :(得分:0)

很明显,solarc是正确的,但是我没有足够的代表对此发表评论,所以我在这里只添加了一点。

如果您在读取json文件(或json的纯文本文件)时遇到问题,请尝试通过json验证程序(即https://jsonlint.com/)放入数据或示例数据。这样可以节省您调试的时间。

相关问题