搜索
首页后端开发Python教程爬虫的解析方式一:JOSN解析

众多语言都能进行爬虫,但基于python的爬虫显得更加简洁,方便。爬虫也成了python语言中必不可少的一部分。爬虫解析数据的方式有很多种,在上一篇给大家介绍的是爬虫能获取什么样的数据和具体的解析方式,本篇给大家带来的是JSON解析。

zz.jpg

JSON

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。

对象:

对象在js中表示为{ }括起来的内容,数据结构为 { key:value, key:value, ... }的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是数字、字符串、数组、对象这几种。

数组:

数组在js中是中括号[ ]括起来的内容,数据结构为 ["Python", "javascript", "C++", ...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。适用于进行数据交互的场景,比如网站前台与后台之间的数据交互。

import json
def resolveJson(path):
    file = open(path, "rb")
    fileJson = json.load(file)
    field = fileJson["field"]
    futures = fileJson["futures"]
    type = fileJson["type"]
    name = fileJson["name"]
    time = fileJson["time"]
    return (field, futures, type, name, time)
def output():
    result = resolveJson(path)
    print(result)
    for x in result:
        for y in x:
            print(y)
path = r"C:\Users\dell\Desktop\kt\test.json"
output()

注意函数返回多个值时返回的是一个元组tuple; 

对一个字符串进行for循环的时候会对每个字符进行遍历

Python JSON

本章节我们将为大家介绍如何使用 Python 语言来编码和解码 JSON 对象。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

JSON 函数

使用 JSON 函数需要导入 json 库:import json。

函数                                                描述

json.dumps                将 Python 对象编码成 JSON 字符串

json.loads                   将已编码的 JSON 字符串解码为 Python 对象

json.dumps

json.dumps                用于将 Python 对象编码成 JSON 字符串。

语法

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

实例

以下实例将数组编码为 JSON 格式数据:

#!/usr/bin/python
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
json = json.dumps(data)
print json

以上代码执行结果为:

[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]

使用参数让 JSON 数据格式化输出:

>>> import json
>>> print json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
{
    "a": "Runoob",
    "b": 7
}

python 原始类型向 json 类型的转化对照表:

Python                                          JSON

dict                                                object

list, tuple                                        array

str, unicode                                    string

int, long, float                               number

True                                                 true

False                                                false

None                                                 null

json.loads

json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

实例

以下实例展示了Python 如何解码 JSON 对象:

<pre class="brush:php;toolbar:false">
#!/usr/bin/python
import json
jsonData = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
text = json.loads(jsonData)
print text

以上代码执行结果为:

{u&#39;a&#39;: 1, u&#39;c&#39;: 3, u&#39;b&#39;: 2, u&#39;e&#39;: 5, u&#39;d&#39;: 4}

json 类型转换到 python 的类型对照表:

JSON                                 Python

object                                  dict

array                                     list

string                                unicode

number (int)                     int, long

number (real)                       float

true                                      True

false                                     False

null                                       None

使用第三方库:Demjson

Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。

Github 地址:https://github.com/dmeranda/demjson

官方地址:http://deron.meranda.us/python/demjson/

环境配置

在使用 Demjson 编码或解码 JSON 数据前,我们需要先安装 Demjson 模块。本教程我们会下载 Demjson 并安装:

$ tar -xvzf demjson-2.2.3.tar.gz
$ cd demjson-2.2.3
$ python setup.py install

JSON 函数

函数                                                    描述

encode                         将 Python 对象编码成 JSON 字符串

decode                         将已编码的 JSON 字符串解码为 Python 对象

encode

Python encode() 函数用于将 Python 对象编码成 JSON 字符串。

语法

demjson.encode(self, obj, nest_level=0)


实例

以下实例将数组编码为 JSON 格式数据:

<pre class="brush:php;toolbar:false">
#!/usr/bin/python
import demjson
data = [ { &#39;a&#39; : 1, &#39;b&#39; : 2, &#39;c&#39; : 3, &#39;d&#39; : 4, &#39;e&#39; : 5 } ]
json = demjson.encode(data)
print json

以上代码执行结果为:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]


decode

Python 可以使用 demjson.decode() 函数解码 JSON 数据。该函数返回 Python 字段的数据类型。

语法

demjson.decode(self, txt)

实例

以下实例展示了Python 如何解码 JSON 对象:

<pre class="brush:php;toolbar:false">
#!/usr/bin/python
import demjson
json = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
text = demjson.decode(json)
print  text

以上代码执行结果为:

{u&#39;a&#39;: 1, u&#39;c&#39;: 3, u&#39;b&#39;: 2, u&#39;e&#39;: 5, u&#39;d&#39;: 4}

以上是爬虫的解析方式一:JOSN解析的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:CSDN。如有侵权,请联系admin@php.cn删除
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!