keywords: python json
source: http://txw1958.cnblogs.com/
先看下JSON的語法規則:
JSON 語法規則
JSON 語法是 JavaScript 對象表示法語法的子集。
- 數據在名稱/值對中
- 數據由逗號分隔
- 花括號保存對象
- 方括號保存數組
JSON 名稱/值對
JSON 數據的書寫格式是:名稱/值對。
名稱/值對包括字段名稱(在雙引號中),后面寫一個冒號,然后是值:
"firstName" : "John"
這很容易理解,等價於這條 JavaScript 語句:
firstName = "John"
JSON 值
JSON 值可以是:
- 數字(整數或浮點數)
- 字符串(在雙引號中)
- 邏輯值(true 或 false)
- 數組(在方括號中)
- 對象(在花括號中)
- null
現在有這樣一個數據,如下所示:
{
url: 'http://txw1958.cnblogs.com',
uid: 100000
}
它的key不帶引號,另外url的值 http://txw1958.cnblogs.com 是單引號,不是雙引號
在網站 http://jsonlint.com/ 使用JSON驗證器 驗證一下,第一個錯誤就是url不是string類型,不認識你老人家
Results Parse error on line 1: { url: 'http: //txw195 -----^ Expecting 'STRING', '}'
下面這條語句可以將這樣的不規則json轉換成規則的dict格式
eval(blog, type('Dummy', (dict,), dict(__getitem__=lambda s,n:n))())
看結果
U:\>python3 Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> blog = ''' ... { ... url: 'http://txw1958.cnblogs.com', ... uid: 100000 ... } ... ''' >>> >>> type(blog) <class 'str'> >>> >>> agent = eval(blog, type('Dummy', (dict,), dict(__getitem__=lambda s,n:n))()) >>> >>> type(agent) <class 'dict'> >>> >>> agent {'url': 'http://txw1958.cnblogs.com', 'uid': 100000} >>>
分析
eval(blog, type('Dummy', (dict,), dict(__getitem__=lambda s,n:n))())
待續......