TranslateProject/published/20190716 Save and load Python data with JSON.md
Martin♡Adele 38dd7895dd
Merge (#3)
* PART

* TSL

PART 2

* 完成翻译 (╯°Д°)╯ ┻━┻

* translated by hopefully2333

translated by hopefully2333

* 申领原文

* Update 20190715 What is POSIX- Richard Stallman explains.md

* 提交译文:20190710 Test 200- Linux And Unix Operating Systems Online For Free

* 提交译文:20190710 Test 200- Linux And Unix Operating Systems Online For Free

* TSL

初译

* TSL:20190708 10 ways to get started with Linux

* APL:20190714 Excellent- Ubuntu LTS Users Will Now Get the Latest Nvidia Driver Updates -No PPA Needed Anymore

* TSL&PRF:20190714 Excellent- Ubuntu LTS Users Will Now Get the Latest Nvidia Driver Updates -No PPA Needed Anymore.md

* PUB

@wxy https://linux.cn/article-11110-1.html

* 选题: 20190716 Security scanning your DevOps pipeline

sources/tech/20190716 Security scanning your DevOps pipeline.md

* 选题: 20190716 Save and load Python data with JSON

sources/tech/20190716 Save and load Python data with JSON.md

* 选题: 20190716 Become a lifelong learner and succeed at work

sources/tech/20190716 Become a lifelong learner and succeed at work.md

* Translated

* translated

* translating

* 提交翻译

* 提交翻译

* update

* heguangzhi  is  translating

* PRF

@vizv

* heguangzhi translated

* leemeans translating

leemeans translating 7 deadly sins of documentation

* PRF

@vizv

* PUB

@vizv https://linux.cn/article-11113-1.html

* PRF

@geekpi

* PUB

@geekpi https://linux.cn/article-11115-1.html

* PRF

@0x996 翻译的不错!恭喜你,完成了第一篇翻译!

* PRF

@WangYueScream 这篇翻译的很好呀

* PUB

@WangYueScream https://linux.cn/article-11116-1.html

* 选题: 20190717 Bond WiFi and Ethernet for easier networking mobility

sources/tech/20190717 Bond WiFi and Ethernet for easier networking mobility.md

* 选题: 20190718 Epic Games Backs Blender Foundation with $1.2m Epic MegaGrants

sources/tech/20190718 Epic Games Backs Blender Foundation with -1.2m Epic MegaGrants.md

* 选题: 20190717 Start tinkering with the Circuit Playground Express

sources/tech/20190717 Start tinkering with the Circuit Playground Express.md

* 选题: 20190717 Get going with EtherCalc, a web-based alternative to Google Sheets

sources/tech/20190717 Get going with EtherCalc, a web-based alternative to Google Sheets.md

* 选题: 20190717 How to install Kibana on MacOS

sources/tech/20190717 How to install Kibana on MacOS.md

* 选题: 20190717 Public internet should be all software-defined

sources/talk/20190717 Public internet should be all software-defined.md

* 选题: 20190717 How edge computing is driving a new era of CDN

sources/talk/20190717 How edge computing is driving a new era of CDN.md

* 选题: 20190717 Mastering user groups on Linux

sources/tech/20190717 Mastering user groups on Linux.md

* 选题: 20190717 MPLS is hanging on in this SD-WAN world

sources/talk/20190717 MPLS is hanging on in this SD-WAN world.md

* 选题: 20190716 Server hardware makers shift production out of China

sources/talk/20190716 Server hardware makers shift production out of China.md

* translated

* translating

* PUB

@0x996 本文首发地址: https://linux.cn/article-11118-1.html
您的 LCTT 专页地址: https://linux.cn/lctt/0x996
请注册领取 LCCN: https://lctt.linux.cn/

* Rename sources/tech/20190718 Epic Games Backs Blender Foundation with -1.2m Epic MegaGrants.md to sources/news/20190718 Epic Games Backs Blender Foundation with -1.2m Epic MegaGrants.md

* Update 20171226 Top 10 Microsoft Visio Alternatives for Linux.md

* Translated

* f

* PRF

@qfzy1233

* PUB

@qfzy1233 https://linux.cn/article-11119-1.html

* 选题: 20190718 What you need to know to be a sysadmin

sources/tech/20190718 What you need to know to be a sysadmin.md

* 选题: 20190718 Redirect a GitHub Pages site with this HTTP hack

sources/tech/20190718 Redirect a GitHub Pages site with this HTTP hack.md

* 选题: 20190718 How to apply 'release early, release often' to build a better brand

sources/tech/20190718 How to apply -release early, release often- to build a better brand.md

* 选题: 20190718 Smart cities offer window into the evolution of enterprise IoT technology

sources/talk/20190718 Smart cities offer window into the evolution of enterprise IoT technology.md

* PRF

@robsean 这篇翻译的很认真

* PUB

@robsean https://linux.cn/article-11120-1.html

* APL:20190718 Epic Games Backs Blender Foundation with -1.2m Epic MegaGrants.md

* TSL&PRF:20190718 Epic Games Backs Blender Foundation with -1.2m Epic MegaGrants.md

* PUB:20190718 Epic Games Backs Blender Foundation with -1.2m Epic MegaGrants.md

@wxy https://linux.cn/article-11121-1.html

* translating

* translated

* translating

* heguangzhi  translated

* translated

* translated

* heguangzhi tranlated

* APL:20190717 Mastering user groups on Linux

* PRF

@MjSeven

* PUB

@MjSeven https://linux.cn/article-11123-1.html

* 选题: 20190719 Modifying Windows local accounts with Fedora and chntpw

sources/tech/20190719 Modifying Windows local accounts with Fedora and chntpw.md

* 选题: 20190719 Buying a Linux-ready laptop

sources/tech/20190719 Buying a Linux-ready laptop.md

* 选题: 20190718 Worst DNS attacks and how to mitigate them

sources/talk/20190718 Worst DNS attacks and how to mitigate them.md

* PRF

@wxy

* PUB

@wxy https://linux.cn/article-11124-1.html

* PRF

@geekpi

* PUB

@geekpi https://linux.cn/article-11125-1.html

* hankchow translating

* hankchow translated

* hankchow translated

* 申请翻译 20190718 What you need to know to be a sysadmin.md

申请翻译 20190718 What you need to know to be a sysadmin.md

* PRF

@geekpi

* PUB

@geekpi https://linux.cn/article-11128-1.html

* PRF

@heguangzhi

* PUB

@heguangzhi https://linux.cn/article-11130-1.html

* PRF

@hopefully2333 原文逻辑不通,我做了段落调整

* PUB

@hopefully2333 https://linux.cn/article-11132-1.html

* PRF

@HankChow

* PUB

@HankChow https://linux.cn/article-11133-1.html

* 选题: 20190720 How to Upgrade Debian 9 (Stretch) to Debian 10 (Buster) via Command Line

sources/tech/20190720 How to Upgrade Debian 9 (Stretch) to Debian 10 (Buster) via Command Line.md

* translated

* translating

* APL:20190717 How to install Kibana on MacOS

* PRF

* TSL&PRF

* PUB

@wxy https://linux.cn/article-11135-1.html

* 选题: 20190723 How to Create a User Account Without useradd Command in Linux?

sources/tech/20190723 How to Create a User Account Without useradd Command in Linux.md

* 选题: 20190722 How to run virtual machines with virt-manager

sources/tech/20190722 How to run virtual machines with virt-manager.md

* 选题: 20190723 8 Best Open Source CRM Software

sources/tech/20190723 8 Best Open Source CRM Software.md

* Revert "Revert "超期回收: sources/tech/20131228 Introduction to Clojure - Modern dialect of Lisp (Part 1).md""

This reverts commit 359e0506a2.

* PRF

@ZhiW5217 恭喜你完成了第一篇翻译。

* PUB

@ZhiW5217 本文首发地址: https://linux.cn/article-11138-1.html
你的 LCTT 专页地址: https://linux.cn/lctt/ZhiW5217
请注册领取你的 LCCN: https://lctt.linux.cn/

* Translating

* translated

* translated

* PRF

@geekpi

* PUB

@geekpi https://linux.cn/article-11141-1.html
2019-07-24 00:38:37 +08:00

5.7 KiB
Raw Blame History

使用 Python 处理 JSON 格式的数据

如果你不希望从头开始创造一种数据格式来存放数据JSON 是一个很好的选择。如果你对 Python 有所了解,就更加事半功倍了。下面就来介绍一下如何使用 Python 处理 JSON 数据。

Cloud and databsae incons

JSON 的全称是 JavaScript 对象表示法JavaScript Object Notation。这是一种以键值对的形式存储数据的格式,并且很容易解析,因而成为了一种被广泛使用的数据格式。另外,不要因为 JSON 名称而望文生义JSON 并不仅仅在 JavaScript 中使用,它也可以在其它语言中使用。下文会介绍它是如何在 Python 中使用的。

首先我们给出一个 JSON 示例:

{
    "name":"tux",
    "health":"23",
    "level":"4"
}

上面是一个和编程语言无关的原生 JSON 数据。熟悉 Python 的人会看出来这个 JSON 数据跟 Python 中的字典dictionary长得很像。而这两者之间确实非常相似,如果你对 Python 中的列表和字典数据结构有一定的理解,那么 JSON 理解起来也不难。

使用字典存放数据

如果你的应用需要存储一些结构复杂的数据,不妨考虑使用 JSON 格式。对比你可能曾经用过的自定义格式的文本配置文件JSON 提供了更加结构化的可递归的存储格式。同时Python 自带的 json 模块已经提供了可以将 JSON 数据导入/导出应用时所需的所有解析库。因此,你不需要针对 JSON 自行编写代码进行解析而其他开发人员在与你的应用进行数据交互的时候也不需要去解析新的数据格式。正是这个原因JSON 在数据交换时被广泛地采用了。

以下是一段在 Python 中使用嵌套字典的代码:

#!/usr/bin/env python3

import json

# instantiate an empty dict
team = {}

# add a team member
team['tux'] = {'health': 23, 'level': 4}
team['beastie'] = {'health': 13, 'level': 6}
team['konqi'] = {'health': 18, 'level': 7}

这段代码声明了一个名为 team 的字典,并初始化为一个空字典。

如果要给这个字典添加内容,首先需要创建一个键,例如上面示例中的 tuxbeastiekonqi,然后为这些键一一提供对应的值。上面示例中的值由一个个包含游戏玩家信息的字典充当。

字典是一种可变的变量。字典中的数据可以随时添加、删除或更新。这样的特性使得字典成为了应用程序存储数据的极好选择。

使用 JSON 格式存储数据

如果存放在字典中的数据需要持久存储,这些数据就需要写到文件当中。这个时候就需要用到 Python 中的 json 模块了:

with open('mydata.json', 'w') as f:
    json.dump(team, f)

上面的代码首先创建了一个名为 mydata.json 的文件,然后以写模式打开了这个文件,这个被打开的文件以变量 f 表示(当然也可以用任何你喜欢的名称,例如 fileoutput 等)。而 json 模块中的 dump() 方法则是用于将一个字典输出到一个文件中。

从应用中导出数据就是这么简单,同时这些导出的数据是结构化的、可理解的。现在可以查看导出的数据:

$ cat mydata.json
{"tux": {"health": 23, "level": 4}, "beastie": {"health": 13, "level": 6}, "konqi": {"health": 18, "level": 7}}

从 JSON 文件中读取数据

如果已经将数据以 JSON 格式导出到文件中了,也有可能需要将这些数据读回到应用中去。这个时候,可以使用 Python json 模块中的 load() 方法:

#!/usr/bin/env python3

import json

f = open('mydata.json')
team = json.load(f)

print(team['tux'])
print(team['tux']['health'])
print(team['tux']['level'])

print(team['beastie'])
print(team['beastie']['health'])
print(team['beastie']['level'])

# when finished, close the file
f.close()

这个方法实现了和保存文件大致相反的操作。使用一个变量 f 来表示打开了的文件,然后使用 json 模块中的 load() 方法读取文件中的数据并存放到 team 变量中。

其中的 print() 展示了如何查看读取到的数据。在过于复杂的字典中迭代调用字典键的时候有可能会稍微转不过弯来,但只要熟悉整个数据的结构,就可以慢慢摸索出其中的逻辑。

当然,这里使用 print() 的方式太不灵活了。你可以将其改写成使用 for 循环的形式:

for i in team.values():
    print(i)

使用 JSON

如上所述,在 Python 中可以很轻松地处理 JSON 数据。因此只要你的数据符合 JSON 的模式,就可以选择使用 JSON。JSON 非常灵活易用,下次使用 Python 的时候不妨尝试一下。


via: https://opensource.com/article/19/7/save-and-load-data-python-json

作者:Seth Kenlon 选题:lujun9972 译者:HankChow 校对:wxy

本文由 LCTT 原创编译,Linux中国 荣誉推出