언어&플랫폼/python

[python] json decode

cozyboy 2013. 12. 10. 17:29
json 형식의 str을 json으로 변환

import json


def testJson(output):

    try:

        decoded = json.loads(output)

        print decoded

        print  decoded['stats']['total_space']

        #print "JSON parsing example: ", decoded['stats']['total_space']

        #print "Complex JSON parsing example: ", decoded['two']['list'][1]['item']

    except (ValueError, KeyError, TypeError):

        print "JSON format error




json, pretty json format.

    @staticmethod             

    def decodeJson(output):   

        '''

        Info : 

            Convert json formed string to json

        --------------------------------------------------------------

        Parameter:

            output - json formated String

        --------------------------------------------------------------

        Return:

            if success decode 

                return output(formated json)

            else 

                return -1

        '''

        try:

            decoded = json.loads(output)   

            return decoded

        except (ValueError, KeyError, TypeError):

            if DEBUG: print "JSON format error[decodeJson()]"

            return -1

        

    @staticmethod

    def encodePrettyJson(output):  

        try:

            decoded = json.dumps(output, sort_keys=True, indent=4, separators=(',', ': '))

            return decoded

        except (ValueError, KeyError, TypeError):

            if DEBUG: print "JSON format error[encodePrettyJson()]"

            return -1

       



참조 : http://docs.python.org/2/library/json.html