簡體   English   中英

Python JSON轉儲不起作用

[英]Python JSON dumps not working

我有一個像這樣的JSON文件

$ cat a.json
{
        "a" : 1,
        "b" : [ 2 , 3 ],
        "c" : {
                "x" : 1,
                "y" : [ 2 , 3 ]
        }
}

我正在嘗試加載和轉儲數據,但是轉儲部分無法正常工作。

我檢查了我的代碼是否能夠加載文件,但是由於某些奇怪的原因,無法使用json.dumps()將其打印到終端

我的代碼:

$ cat jlo.py
import json
import pprint

class JLO():
        def __init__(self):
                try:
                        with open("a.json",'r') as inFile:
                                config = json.load(inFile)
                except Exception as e:
                        print "Can't read JSON config" + str(e)
                        exit(1)
                self.config = config

print "Main"
print "================"
jlo = JLO();
json.dumps(jlo.config, sort_keys=True, indent=4)
print "================"
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(jlo.config)
print "================"

輸出:

$ python jlo.py
Main
================
================
{   u'a': 1, u'b': [2, 3], u'c': {   u'x': 1, u'y': [2, 3]}}
================

我在使用Python 2.6

工作示例1 —使用Python 2.6.92.7.103.2.53.4.33.5.0測試

import json


class JLO():

    def __init__(self):
        self.data = ''

    def config(self, json_file=''):
        try:
            with open(json_file, 'r') as json_data:
                self.data = json.load(json_data)
        except Exception as e:
            print('Can\'t read JSON config - ' + str(e))
            exit(0)


if __name__ == "__main__":
    jlo = JLO()
    jlo.config(json_file='a.json')

    print('Main')
    print('================')
    print(jlo.data)
    print('================')
    print(json.dumps(jlo.data,
                     sort_keys=True, indent=4, separators=(',', ': ')))
    print('================')

輸出量

Main
================
{u'a': 1, u'c': {u'y': [2, 3], u'x': 1}, u'b': [2, 3]}
================
{
    "a": 1,
    "b": [
        2,
        3
    ],
    "c": {
        "x": 1,
        "y": [
            2,
            3
        ]
    }
}
================

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM