python3.2 解析JSON

json.txt

{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }

工具类 CommonUtil.py

#!/usr/bin/python
#__*__coding:utf-8__*__

"""
打印分隔符----用于格式化输出
"""
def print_lines(char='*', num=30) :
    print(char * num)

"""
合并多行文本成一行
"""
def merge_lines(filePath):
    data = (x.strip() for x in open(filePath))
    return "".join(data)

if __name__ == "__main__" :
    line = merge_lines(r"f:/json.txt")
    print(line)

解析类 my_json_parser.py

#!/usr/bin/python
#__*__coding:utf-8__*__


"""
My JSON Parser
"""


import json
import CommonUtil


"""
第一种方法
"""
def method_one():
    lines = CommonUtil.merge_lines(r'F:\json.txt')
    data = json.dumps(lines, sort_keys=True)


    # 为嘛要转两回呢???
    json_obj = json.JSONDecoder().decode(data)
    json_obj = json.JSONDecoder().decode(json_obj)
    for obj in json_obj :
        first_level_obj = json_obj[obj]
        for prop in first_level_obj :
            print(prop)
            for _prop in prop :
                print("%s=%s" % (_prop, prop[_prop]))
            CommonUtil.print_lines()


"""
第二种方法
"""
def method_two():
    lines = CommonUtil.merge_lines(r'F:\json.txt')
    json.loads(lines, object_pairs_hook=cls_hook)


def cls_hook(dct):
    print(dct)
    for k,v in dct:
        print("%s=%s" % (k, v))
    CommonUtil.print_lines()


if __name__ == '__main__':
    # method_one()
    method_two()









其他:详见http://docs.python.org/2/library/json.html

#!/usr/bin/python
#__*__coding:utf-8__*__

import json
from io import StringIO
import decimal

# dumps
def _dumps():
    data = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
    sorted_data = json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
    print(data)
    print(sorted_data)

# Serialize ``obj`` as a JSON formatted stream to ``fp``
def _dump():
    io = StringIO()
    json.dump(['streaming API'], io)
    print(io.getvalue())

# Compact encoding:
def compact_encoding():
    print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')))

#Pretty printing
def pretty_printing():
    print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))

#Decoding JSON
def decoding_json():
    print(json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]'))
    io = StringIO('["streaming API"]')
    print(json.load(io))

def as_complex(dct):
    if '__complex__' in dct:
        return complex(dct['real'], dct['imag'])
    return dct

#Specializing JSON object decoding:
def special() :
    print(json.loads('{"__complex__": true, "real": 1, "imag": 2}', object_hook=as_complex))
    print(json.loads('1.1', parse_float=decimal.Decimal))
    print(json.dumps(2 + 1j, cls=ComplexEncoder))
    print(list(ComplexEncoder().iterencode(2 + 1j)))

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return [obj.real, obj.imag]
        return json.JSONEncoder.default(self, obj)


if __name__ == '__main__':
    _dumps()
    _dump()
    compact_encoding()
    pretty_printing()
    decoding_json()
    special()


你可能感兴趣的:(python3.2 解析JSON)