博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ruby 和 Python3 读取 yaml 和 json 格式文件
阅读量:4229 次
发布时间:2019-05-26

本文共 5791 字,大约阅读时间需要 19 分钟。

 (JavaScript Object Notation) 是一种以人可读的文本表示对象的方法。 它已经变成 NoSQL 世界交换数据的事实标准。当一个对象被序列化成为 JSON,它被称为一个 JSON 文档 。由于 JSON 数据格式比较简单, 易于读写, 格式都是压缩的, 占用带宽小,易于解析等特点,使得它在各种场合下都十分受欢迎,客户端 JavaScript 可以简单的通过 eval() 进行JSON数据的读取,包括 Java,JavaScript,Perl,PHP,Python,Ruby等服务器端语言(几乎大部分语言都支持对 json文件的解析), 便于服务器端的解析。

但是在相同情况下,与 json 相同内容的 yaml 文件却更加简洁,我们先来看看样例(两个文件表达的内容一样):

# test.json{  "apiVersion": "v1",  "kind": "Pod",  "metadata": {    "name": "pod-redis",    "labels": {      "name": "redis"    }  },  "spec": {    "restartPolicy": "Always",    "nodeSelector": {      "zone": "node1"    },    "containers": [      {        "name": "pod-redis",        "image": "docker.io/redis",        "imagePullPolicy": "Never",        "ports": [          {            "containerPort": 6379,            "hostPort": 8080          }        ]      }    ]  }}
# test.yamlapiVersion: v1kind: Podmetadata:  name: pod-redis  labels:    name: redisspec:  restartPolicy: Always  nodeSelector:    zone: node1  containers:    - name: pod-redis      image: docker.io/redis      imagePullPolicy: Never      ports:        - containerPort: 6379          hostPort: 8080

Ruby 读取

yaml 和 json 格式文件的读取:

# Rubyrequire 'json'require 'yaml'# 解析出来的都是 Ruby 中的 Hash 对象# puts JSON.parse(File.read('test.json'))puts JSON.load(File.open('test.json'))# puts YAML.load_file("test.yaml")puts YAML.load(File.open("test.yaml"))------------------------------------------------------------D:\Ruby23-x64\bin\ruby.exe D:/MyProject/Ruby/workspace/test.rb{"apiVersion"=>"v1", "kind"=>"Pod", "metadata"=>{"name"=>"pod-redis", "labels"=>{"name"=>"redis"}}, "spec"=>{"restartPolicy"=>"Always", "nodeSelector"=>{"zone"=>"node1"}, "containers"=>[{"name"=>"pod-redis", "image"=>"docker.io/redis", "imagePullPolicy"=>"Never", "ports"=>[{"containerPort"=>6379, "hostPort"=>8080}]}]}}{"apiVersion"=>"v1", "kind"=>"Pod", "metadata"=>{"name"=>"pod-redis", "labels"=>{"name"=>"redis"}}, "spec"=>{"restartPolicy"=>"Always", "nodeSelector"=>{"zone"=>"node1"}, "containers"=>[{"name"=>"pod-redis", "image"=>"docker.io/redis", "imagePullPolicy"=>"Never", "ports"=>[{"containerPort"=>6379, "hostPort"=>8080}]}]}}Process finished with exit code 0

hash object 的 pretty print :

# Rubyrequire 'json'require 'yaml'require 'pp'pp JSON.load(File.open('test.json'))putspp YAML.load(File.open("test.yaml"))------------------------------------------------------------D:\Ruby23-x64\bin\ruby.exe D:/MyProject/Ruby/workspace/test.rb{"apiVersion"=>"v1", "kind"=>"Pod", "metadata"=>{"name"=>"pod-redis", "labels"=>{"name"=>"redis"}}, "spec"=>  {"restartPolicy"=>"Always",   "nodeSelector"=>{"zone"=>"node1"},   "containers"=>    [{"name"=>"pod-redis",      "image"=>"docker.io/redis",      "imagePullPolicy"=>"Never",      "ports"=>[{"containerPort"=>6379, "hostPort"=>8080}]}]}}{"apiVersion"=>"v1", "kind"=>"Pod", "metadata"=>{"name"=>"pod-redis", "labels"=>{"name"=>"redis"}}, "spec"=>  {"restartPolicy"=>"Always",   "nodeSelector"=>{"zone"=>"node1"},   "containers"=>    [{"name"=>"pod-redis",      "image"=>"docker.io/redis",      "imagePullPolicy"=>"Never",      "ports"=>[{"containerPort"=>6379, "hostPort"=>8080}]}]}}Process finished with exit code 0

Python 读取

yaml 和 json 格式文件的读取:

import jsonimport yamlwith open('test.yaml', 'r', encoding='utf-8') as f:    yaml_str = f.read()dict_obj = yaml.load(yaml_str, yaml.FullLoader)print(dict_obj)# json.load(open('test.json', 'rb'))# or# with open("centos.json", 'rb') as f:#     dict_obj = json.load(f)with open("test.json") as f:    json_str = f.read()dict_obj = json.loads(json_str)print(dict_obj)------------------------------------------------------------"D:\Program Files\Python36\python3.exe" D:/MyProject/Python/workspace/test.py{'apiVersion': 'v1', 'kind': 'Pod', 'metadata': {'name': 'pod-redis', 'labels': {'name': 'redis'}}, 'spec': {'restartPolicy': 'Always', 'nodeSelector': {'zone': 'node1'}, 'containers': [{'name': 'pod-redis', 'image': 'docker.io/redis', 'imagePullPolicy': 'Never', 'ports': [{'containerPort': 6379, 'hostPort': 8080}]}]}}{'apiVersion': 'v1', 'kind': 'Pod', 'metadata': {'name': 'pod-redis', 'labels': {'name': 'redis'}}, 'spec': {'restartPolicy': 'Always', 'nodeSelector': {'zone': 'node1'}, 'containers': [{'name': 'pod-redis', 'image': 'docker.io/redis', 'imagePullPolicy': 'Never', 'ports': [{'containerPort': 6379, 'hostPort': 8080}]}]}}Process finished with exit code 0

json_str object 的 pretty print :

import jsonimport yamlwith open('test.yaml', 'r', encoding='utf-8') as f:    yaml_str = f.read()dict_obj = yaml.load(yaml_str, yaml.FullLoader)print(json.dumps(dict_obj, indent=2))print()with open("test.json") as f:    json_str = f.read()dict_obj = json.loads(json_str)print(json.dumps(dict_obj, indent=2))------------------------------------------------------------"D:\Program Files\Python36\python3.exe" D:/MyProject/Python/workspace/test.py{  "apiVersion": "v1",  "kind": "Pod",  "metadata": {    "name": "pod-redis",    "labels": {      "name": "redis"    }  },  "spec": {    "restartPolicy": "Always",    "nodeSelector": {      "zone": "node1"    },    "containers": [      {        "name": "pod-redis",        "image": "docker.io/redis",        "imagePullPolicy": "Never",        "ports": [          {            "containerPort": 6379,            "hostPort": 8080          }        ]      }    ]  }}{  "apiVersion": "v1",  "kind": "Pod",  "metadata": {    "name": "pod-redis",    "labels": {      "name": "redis"    }  },  "spec": {    "restartPolicy": "Always",    "nodeSelector": {      "zone": "node1"    },    "containers": [      {        "name": "pod-redis",        "image": "docker.io/redis",        "imagePullPolicy": "Never",        "ports": [          {            "containerPort": 6379,            "hostPort": 8080          }        ]      }    ]  }}Process finished with exit code 0

 

转载地址:http://mcjqi.baihongyu.com/

你可能感兴趣的文章
zookeeper安装启动的一些问题
查看>>
rabbitmq命令执行报错command not found
查看>>
rabbitmq基础知识介绍及总结
查看>>
StackOverFlow异常记录
查看>>
SpringMvc4.1:注解JsonView与泛型返回类
查看>>
SpringMVC+Mybatis+事务回滚+异常封装返回
查看>>
计算机网络实验报告(三):Cisco Packet Tracer 实验
查看>>
嵌入式系统基础学习笔记(九):基于 SPI 协议在 0.96 寸 OLED上【平滑显示汉字】及【温湿度数据采集显示】
查看>>
嵌入式系统基础学习笔记(十):
查看>>
网络通信编程学习笔记(七):Java与MQTT
查看>>
人工智能与机器学习学习笔记(二)
查看>>
Run Your Own Web Server Using Linux & Apache
查看>>
Java I/O
查看>>
SQL Server 2005 T-SQL Recipes: A Problem-Solution Approach
查看>>
Core Python Programming
查看>>
Creating Database Web Applications with PHP and ASP
查看>>
ASP.NET 2.0 Demystified
查看>>
Pattern-Oriented Software Architecture, Volume 2, Patterns for Concurrent and Networked Objects
查看>>
Pattern-Oriented Software Architecture, Volume 1: A System of Patterns
查看>>
Database Programming with Visual Basic® .NET and ADO.NET: Tips, Tutorials, and Code
查看>>