python3处理不标准json数据
2024-10-02 02:09:58
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))())
待续......
最新文章
- 操作数数据类型 ntext 对于 max 运算符无效
- Runner站立会议02
- 程序源系统与当前系统不一致:Carry out repairs in non-original systems only if urgent
- Win7精简成功后的总结
- python基础知识---变量
- nutch-2.2.1 hadoop-1.2.1 hbase-0.92.1 集群部署
- (转载)PHP 提示和技巧
- JQUERY1.9学习笔记 之基本过滤器(五) 大于选择器
- React Native基础&;入门教程:以一个To Do List小例子,看props和state
- Selective Search for Object Recognition(理解)
- 详解Asp.Net Core 2.1+的视图缓存(响应缓存)
- 【公众号系列】SAP S/4 HANA 1809请查收
- 902. Kth Smallest Element in a BST
- python第七十一天---堡垒机
- 洛谷P3724 大佬 [AH2017/HNOI2017] dp+bfs
- scrapy学习--安装
- eclipse 中springboot2.0整合jsp 出现No Java compiler available for configuration options compilerClassName
- web api 获取传过来的Json
- nagios监控mysql
- Fireworks如何制作透明窗口PNG
热门文章
- gvim 窗口最大化启动
- 一起学libcef--给你的浏览器删除cookie
- 使用perl读取Excel
- centos7安装jdk+tomcat+nginx+mysql
- Nginx的一些介绍
- web报表工具FineReport经常使用函数的使用方法总结(文本函数)
- 定义变量let,const
- springmvc中controller内方法跳转forward?redirect?
- [Angular] Using the platform agnostic Renderer &; ElementRef
- 解决离线Could not parse configuration:hibernate.cfg.xml错误