# -*- coding: UTF-8 -*-
import ast
def getJsonStr(obj):
    '''
    @summary: 将字典或集合类型数据结构转成json字符串
    @param obj: 字典或集合类型数据结构
    '''
    if type(obj) == dict:
        return dict2JsonStr(obj)
    
    if type(obj) == list:
        strObj = "["
        metFirst = False
        for index in range(0, len(obj)):
            strDict = dict2JsonStr(obj[index])
            if True == metFirst:
                strObj = strObj + ', ' + strDict
            else:
                strObj = strObj + strDict 
                metFirst = True 
        strObj = strObj + ']'
        return strObj
    
    return ""

def dict2JsonStr(obj):
    '''
    @summary: 将字典类型数据结构转成json字符串
    @param obj: 字典类型数据结构
    '''
    strDict = "{"
    metFirst = False
    for (key, value) in obj.items():
        value = str(value)
        if True == metFirst:
            strDict = strDict + ', \"' + key + '\":\"' + value + '\"'
        else:
            strDict = strDict + '\"' + key + '\":\"' + value + '\"'
            metFirst = True
    strDict = strDict + '}'
    return strDict

def jsonStr2Dict(strJson):
    '''
    @summary: 将json字符串转成字典数据结构
    @param strJson: json字符串
    '''
    return ast.literal_eval(unicode(strJson))

def dictList2JsonArray(portsInfoList):
    '''
    @summary: 将字典的集合转换为json数组
    @param portsInfoList: 端口的字典列表集合
    @return: 端口信息对应的json数组
    '''
    jsonArray = []
    for portsInfoDict in portsInfoList:
        jsonArray.append("{%s}" % ",".join(['"%s":"%s"' % (key, portsInfoDict.get(key)) for key in portsInfoDict.keys()]))
    return "[%s]" % ",".join(jsonArray)

def jsonArray2DictList(jsonArray):
    '''
    @summary: 将json数组转换为字典的集合
    @param jsonArray: json数组
    @return: json数组对应的字典的集合
    '''
    if jsonArray is None or len(jsonArray) <=2:
        return None
    jsonArray = jsonArray[1:-1]
    resultDictList = []
    for items in jsonArray.split("},{"):
        resultDict = {}
        for item in items.split("\",\""):
            kv = item.replace("{", "").replace("}", "").replace("\"", "").split(":")
            if len(kv) != 2:
                return resultDictList
            resultDict[kv[0]] = kv[1]
        if len(resultDict.keys()) > 0:
            resultDictList.append(resultDict.copy())
    
    return resultDictList
