json报文、汉字代码与字典遍历(换皮)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/dudu3332/article/details/102630131
#汉字转化及输出
#构建一个简单的json文件
 a = {}
 a['1'] = 2
a['ad'] = 'ertwer'
a['02'] = 'oierte'
a[2] = [1, 'a']
#汉字的传递
a['non_ascii'] = "青团 》 熊猫 ?"
a['ss'] = a.copy()
#按key输出的字典形式
print(json.dumps(a))
#汉字传递不转化为编码 缩进两格
print(json.dumps(a,ensure_ascii=False,indent=2))

#构建一个json报文
SendRegisterVerificationCodejson_txt = """
{
  "header":{
    "funcNo": "IF010002",
    "opStation": "11.11.1.1",
    "appId": "aaaaaa",
    "deviceId": "kk",
    "ver":"wx-1.0",
    "channel": "4"
  },
  "payload": {
    "mobileTel": "13817120001"
  }
}
"""
SendRegisterVerificationCodejson_txt
data_json_test=json.loads(SendRegisterVerificationCodejson_txt)
#遍历报文 按照key value对应形式输出
#构建空字典 方便重组数据
dic_test={}

def json_match_loop(json_source):
    if isinstance(json_source,dict):
        for key in json_source:
            #判断第一层字典的值是否还是字典
            if isinstance(json_source[key],dict):
                print("** key: %s  value: %s" %(key,json_source[key]))
                json_match_loop(json_source[key])
                #好用的字典复制语句
                dic_test[key]=json_source[key]
            else:
                print("** key: %s  value: %s" %(key,json_source[key]))
                dic_test[key] = json_source[key]
json_match_loop(data_json_test)
dic_test
print("dic:"+str(dic_test))
#改变特定键的值 并输出前后字典
def json_check_replace(json_source,key_no_change,value_change):
    if isinstance(json_source,dict):
        for key in json_source:
            if key == key_no_change:
                json_source[key] = value_change
            elif isinstance(json_source[key],dict):
                json_check_replace(json_source[key],key_no_change,value_change)
print("before change: ")
print(data_json_test)
json_check_replace(data_json_test,'funcNo','2342432')
print("after change:")
print(data_json_test)

猜你喜欢

转载自blog.csdn.net/dudu3332/article/details/102630131