`

python 解析 json

阅读更多

#!/usr/bin/env python
import sys;
import simplejson as json;

def GetJsonVal(strJsonFile, lsKey):
    try:
        if len(lsKey) <= 0:
            return [-1, ''];
        
        mapJson = json.load(file(strJsonFile));
        mapVal = mapJson;

        for strKey in lsKey:
            if not mapVal.has_key(strKey):
                return [-2, ''];
            else:
                mapVal = mapVal[strKey];

        return [0, mapVal];           

    except:
        return [-10, ''];

def usage():
    strExe = sys.argv[0];
    print("Usage: %s json_file json_path\nExample:%s  /a.json a/b/c" %(strExe, strExe))
    
if "__main__" == __name__:
    strJson = sys.argv[1];
    lsKey = sys.argv[2:];

    lsRet = GetJsonVal(strJson, lsKey);
    if 0 != lsRet[0]:
        print("get key:%s failed! error code:%s" %('/'.join(lsKey), lsRet[0]));
        sys.exit(lsRet[0]);
    else:
        print(lsRet[1]);
        sys.exit(0);
    
    
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics