获取JSON格式字符的处理

————————日志cat datastore ——————————————————————— 

{
    "freeSize": 193874944,
    "capacity": 287834112,
    "name": "DS_local_1106",
    "datastoreType": 1,
    "id": "DataStore=ad4bee29651cc00"
}
CIE_1111:/home/ycc/python # ./handleJson.py datastore getValue dataStores,,,1,,,name
"DS_local_1106"

CIE_1111:/home/ycc/python # cat datastore
{
  "dataStores" : [ {
    "name" : "DS_NFS_01",
    "id" : "NasDataStore=33b7bf6cb4f72000",
    "capacity" : 82573140,
    "datastoreType" : 3,
    "freeSize" : 10399684
  }, {
    "name" : "DS_local_1106",
    "id" : "DataStore=ad4bee29651cc00",
    "capacity" : 287834112,
    "datastoreType" : 1,
    "freeSize" : 193874944
  }, {
    "name" : "DS_AutoTest_shared",
    "id" : "DataStore=49efda5385313400",
    "capacity" : 104595456,
    "datastoreType" : 2,
    "freeSize" : 101502976
  }, {
    "name" : "DS_AutoTest_saved",
    "id" : "DataStore=695fe423d9191400",
    "capacity" : 65798144,
    "datastoreType" : 2,
    "freeSize" : 59560960
  }, {
    "name" : "DS_Test_shared",
    "id" : "DataStore=51529b271c0de000",
    "capacity" : 628883456,
    "datastoreType" : 1,
    "freeSize" : 627886080
  } ]
}

 

——————————脚本名handleJson.py———————————————————————————————

使用方法:

1、 #  ./handleJson.py datastore getValue dataStores,,,1,,,name

2、# ./handleJson.py datastore getValue dataStores,,,1

——————————————————————————handleJson.py———————————————————————————————

#!/usr/bin/python
# handle JSON format file
# yuchenchen 00000000

'''
Usage:
    ./handleJson.py $destJson 'getValue' keys
    (not finished)./handleJson.py $destJson 'getLen' keys
Examples:
    ./handleJson.py datastore 'getValue' dataStores,,,1,,,name
'''

import sys
import os
import json

# check parameter
if len(sys.argv) < 3:
    sys.exit(1)

# read JSON file
if os.path.isfile(sys.argv[1]):
    f = file( sys.argv[1] )
    s = json.load(f)
else:
    sys.exit(1)

# handle JSON format data
keys = sys.argv[3]

if keys != '' :
    keys = keys.split(',,,')
    for key in keys :
        if key.isdigit() == True:
            s = s[ int(key) ]
        else:
            s = s[key]

# choose function
fun = sys.argv[2]
if fun == "getValue":
    print json.dumps( s, indent = 4 )
elif fun == "getLen":
    sys.exit(1)
    #print json.dumps( s.keys())
else:
    sys.exit(1)


f.close

你可能感兴趣的:(获取JSON格式字符的处理)