json模塊

json是一種輕量級數據交換格式,自行百度去,這裏上乾貨

json.dumps(被轉對象)方法

import json

DB_CONFIG = {
    'user':'root',
    'passwd':'westos',
    'host':'localhost',
    'port':3306,
    'db':'westos01',
    'charset': 'utf8'
}
print  type(DB_CONFIG)   ##查看DB_CONFIG類型,肯定是字典了
transfer_format=json.dumps(DB_CONFIG)  ##通過json的dump方法轉化爲字符串
print transfer_format
print type(transfer_format)    ##字符串類型
--->>結果
<type 'dict'>
{"passwd": "westos", "charset": "utf8", "db": "westos01", "host": "localhost", "user": "root", "port": 3306}
<type 'str'>

markdown中雙引號電腦上正常顯示,手機上查看時會遺失數據,來張截圖
這裏寫圖片描述

json.loads()本地轉化

DB_CONFIG = {
    'user':'root',
    'passwd':'westos',
    'host':'localhost',
    'port':3306,
    'db':'westos01',
    'charset': 'utf8'
}
print  type(DB_CONFIG)
transfer_format=json.dumps(DB_CONFIG)
print transfer_format
print type(transfer_format)

###json.loads()方法
py_json=json.loads(transfer_format)
print py_json
print type(py_json)
--->>結果
<type 'dict'>
{"passwd": "westos", "charset": "utf8", "db": "westos01", "host": "localhost", "user": "root", "port": 3306}
<type 'str'>
###json.loads()方法
{u'passwd': u'westos', u'charset': u'utf8', u'db': u'westos01', u'host': u'localhost', u'user': u'root', u'port': 3306}
<type 'dict'>

這裏寫圖片描述

獲取指定ip地理位置

import json
import urllib
def gethtml(ip):
    url ='http://freegeoip.net/json/%s' %ip
    ##訪問指定連接並讀取網頁內容
    html = urllib.urlopen(url).read()
    return json.loads(html)
addr=gethtml('1.2.3.4')
print addr ##顯示關於ip1.2.3.4的所有信息,返回一字典
print addr['country_name']  ##查看ip1.2.3.4在那個國家
----->>>結果
{u'city': u'Mukilteo', u'region_code': u'WA', u'region_name': u'Washington', u'ip': u'1.2.3.4', u'time_zone': u'America/Los_Angeles', u'longitude': -122.3042, u'metro_code': 819, u'latitude': 47.913, u'country_code': u'US', u'country_name': u'United States', u'zip_code': u'98275'}
United States

這裏寫圖片描述

發佈了102 篇原創文章 · 獲贊 27 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章