언어&플랫폼/python 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




'언어&플랫폼 > python' 카테고리의 다른 글

[python] dictionary 에 dictionary 붙이기  (0) 2013.12.18
[python] 띄어쓰기 제거  (0) 2013.12.10
Tutorial  (0) 2013.12.10
os.popen3와 subprocess.Popen  (0) 2013.12.09
[python] 로컬 ip 얻기  (0) 2013.11.22
posted by cozyboy
: