简体   繁体   中英

Python JSON dumps not working

I have a JSON file like this

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

I am trying to load and dump the data, however the dump part is not working.

I checked that my code is able to load the file but for some strange reason not able to print it to the terminal using json.dumps()

My code:

$ 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 "================"

Output:

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

I am on Python 2.6

Working Example #1 — Tested with Python 2.6.9 and 2.7.10 and 3.2.5 and 3.4.3 and 3.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('================')

Output

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
        ]
    }
}
================

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