python接口保存接口请求数据的json文件json.load()读取文件时在2.x和3.x的那些区分

先来看看3.x
# coding=utf-8
import  json
import requests
data ={"登陆接口":
           {"method": "post",
                    "url": "https://pv.csdn.net/csdnbi",
                    "data": [{"headers":{"component":"enterprise","datatype":"re","version":"v1"},"body":"{\"re\":\"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-\"}"}],
       "header": {"Content-Type": "text/plain;charset=UTF-8"},
        "cookie": {"dc_session_id": "10_1541690279946.617154"},
        "author": "JackChen"
    }
 }

class JsonTransfer(object):
    """3.x以上的json文件读取中文乱码用这个解决,3.x默认utf-8,dump你再加异常很bug"""
    def write_read_json(self):
        with open('./ReadJson.json', 'w')as f:
            json.dump(data,f,ensure_ascii=False,separators=(',',':'),sort_keys=True,indent=3)
        f= open('./ReadJson.json','r')
        dict =json.load(f)
        # print(dict)
        """如果有人还有问题请用以下输出,注意3.x默认encoding=utf-8,你再加就异常了dumps里面"""
        """------------------"""
        report_show = json.dumps(dict,ensure_ascii=False,indent=3,separators=(',', ':'))
        print(report_show)
        """--------------------"""

        cookie=dict['登陆接口']['cookie']
        js =dict['登陆接口']['data']

        url=dict['登陆接口']['url']
        header =dict['登陆接口']['header']
        rep =requests.post(url=url,headers=header,json=js,cookies=cookie)
        return rep.text  #在2.x这里是content也可以的3.x,我都不想吐槽了

if __name__ == "__main__":
   print(JsonTransfer().write_read_json())


C:\Python35\python3.exe C:/Users/Administrator/PycharmProjects/py3project/interface/Paramters/ReadJson2.py
{
   "登陆接口":{
      "cookie":{
         "dc_session_id":"10_1541690279946.617154"
      },
      "data":[
         {
            "body":"{\"re\":\"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-\"}",
            "headers":{
               "version":"v1",
               "datatype":"re",
               "component":"enterprise"
            }
         }
      ],
      "method":"post",
      "header":{
         "Content-Type":"text/plain;charset=UTF-8"
      },
      "url":"https://pv.csdn.net/csdnbi",
      "author":"JackChen"
   }
}

<Response>:
    ok
json文件看看名称中文的第一个都是什么鬼读取出来的都是正常的可以请求,手动改也可以,不过改过后不要再dump写入数据了不然又回来了
ReadJson.json

{
   "��½�ӿ�":{
      "author":"JackChen",
      "cookie":{
         "dc_session_id":"10_1541690279946.617154"
      },
      "data":[
         {
            "body":"{\"re\":\"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-\"}",
            "headers":{
               "component":"enterprise",
               "datatype":"re",
               "version":"v1"
            }
         }
      ],
      "header":{
         "Content-Type":"text/plain;charset=UTF-8"
      },
      "method":"post",
      "url":"https://pv.csdn.net/csdnbi"
   }
}





 

 

2.x的json文件读取,也有bug
# coding=utf-8
"""再老的版本用下面这个utf-8设置,很bug"""
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')

import  json
import requests

data ={"登陆接口":
           {"method": "post",
                    "url": "https://pv.csdn.net/csdnbi",
                    "data": [{"headers":{"component":"enterprise","datatype":"re","version":"v1"},"body":"{\"re\":\"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-\"}"}],
       "header": {"Content-Type": "text/plain;charset=UTF-8"},
        "cookie": {"dc_session_id": "10_1541690279946.617154"},
        "author": "JackChen",
        "bug": "我想吐槽"
    }
 }

class JsonTransfer(object):
    """2.7-3.0以下的版本json文件读取中文乱码用这种可以解决,transefer函数转换json.load()中文编码乱码问题"""
    def transfer(self,obj):
        if isinstance(obj, dict):
            return {self.transfer(key):self.transfer(value) for key,value in obj.iteritems()}
        elif isinstance(obj, list):
            return [self.transfer(element) for element in obj]
        elif isinstance(obj, unicode):
            return obj.encode('utf-8')
        else:
            return obj

    """3.x以上的json文件读取中文乱码用这个解决"""
    def write_read_json(self):
        with open('./ReadJson.json', 'w')as f:
            json.dump(data,f,ensure_ascii=False,separators=(',',':'),sort_keys=True,indent=2,encoding='utf-8')
        f= open('./ReadJson.json','r')
        dt =json.load(f) # 2.x读取出来都是Unicode
        dict =self.transfer(dt) # unicode转换utf-8
        print dict
        print dict['登陆接口']['bug']
        """如果你是要输出报告请用下面转换,请求请用上面"""
        """------------------"""
        #results = json.dumps(dict,ensure_ascii=False,encoding='utf-8',indent=3,separators=(',', ':'))
        # print(results)
        """-------------------"""
        cookie=dict['登陆接口']['cookie']
        js =dict['登陆接口']['data']
        # print dict['登陆接口']['bug']
        url=dict['登陆接口']['url']
        header =dict['登陆接口']['header']
        rep =requests.post(url=url,headers=header,json=js,cookies=cookie)
        print rep.content  #2.x这里content也可以,3.x不可以只能text

if __name__ == "__main__":
    JsonTransfer().write_read_json()

#这是transfer将json文件内容读取出来的unicode转换utf-8
{'\xe7\x99\xbb\xe9\x99\x86\xe6\x8e\xa5\xe5\x8f\xa3': {'author': 'JackChen', 'url': 'https://pv.csdn.net/csdnbi', 'bug': '\xe6\x88\x91\xe6\x83\xb3\xe5\x90\x90\xe6\xa7\xbd', 'header': {'Content-Type': 'text/plain;charset=UTF-8'}, 'cookie': {'dc_session_id': '10_1541690279946.617154'}, 'data': [{'body': '{"re":"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-"}', 'headers': {'datatype': 're', 'version': 'v1', 'component': 'enterprise'}}], 'method': 'post'}}



# print dict['登陆接口']['bug'] :我想吐槽 这个dict数据拿去请求是可以的,但直接当报告你想多了乱码\xe7\x99\xbb\xe9\x99\x86\xe6\x8e\xa5\xe5\x8f\xa3'
<Respinse>:   ok

#results = json.dumps(dict,ensure_ascii=False,encoding='utf-8',indent=3,separators=(',', ':'))
        # print(results)
dumps输出报告格式:
{
   "登陆接口":{
      "author":"JackChen",
      "url":"https://pv.csdn.net/csdnbi",
      "bug":"我想吐槽",
      "header":{
         "Content-Type":"text/plain;charset=UTF-8"
      },
      "cookie":{
         "dc_session_id":"10_1541690279946.617154"
      },
      "data":[
         {
            "body":"{\"re\":\"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-\"}",
            "headers":{
               "datatype":"re",
               "version":"v1",
               "component":"enterprise"
            }
         }
      ],
      "method":"post"
   }
}

不过唯一让我欣慰的是2.x的ReadJson.json文件没有中文显示乱码:
{
  "登陆接口":{
    "author":"JackChen",
    "bug":"我想吐槽",
    "cookie":{
      "dc_session_id":"10_1541690279946.617154"
    },
    "data":[
      {
        "body":"{\"re\":\"ref=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Fverify&mtp=2&mod=ad_popu_282&con=ad_content_3743%2Cad_order_719&uid=chen498858336&ck=-\"}",
        "headers":{
          "component":"enterprise",
          "datatype":"re",
          "version":"v1"
        }
      }
    ],
    "header":{
      "Content-Type":"text/plain;charset=UTF-8"
    },
    "method":"post",
    "url":"https://pv.csdn.net/csdnbi"
  }
}











 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值