首页 > 编程语言 >Python之JSON用法解析

Python之JSON用法解析

时间:2022-10-27 14:58:04浏览次数:40  
标签:hdfs 10 Python json -- JSON --. 解析 root

前景

Python编写HDFS服务安装的过程中,需要将构建好的JSON对象输出到文件,采用那种方式更便捷

方案1

open 函数
    def writeExecCmdCheckActionsFile(self, out_res, check_item):
        """
        输出到文件
        """
        try:
            # host_check_java_env_check.result
            self.hostCheckCustomActionsFilePath = self.hostCheckCustomActionsFilePath + check_item + '.result'
            print("Host check custom action report at " + self.hostCheckCustomActionsFilePath)
            with open(self.hostCheckCustomActionsFilePath, 'w+') as configfile:
                configfile.write(str(out_res))
        except Exception as err:
            logging.error("Can't write host check file at %s :%s " % (self.hostCheckCustomActionsFilePath, err))

上述代码中with open(self.hostCheckCustomActionsFilePath, 'w+') as configfile: 打开了文件流对象 configfile, 用write()方法将字符串写入

write()方法

write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

write()方法不会在字符串的结尾添加换行符('\n'):

注意:configfile.write(str(out_res)) 中,out_res 是一个Python json对象,不是字符串,所以用 str() 将json转为str,然后再写入

如果不想用 str() 方法转换,可以采用如下第二种方案

方案2

JSON模块

导入json库

import json
用法
  • json.dumps() 将Python对象编码成json字符串
  • json.dump() 将Python对象转化为json存储到文件中
  • json.load() 将文件中的json格式转化成Python对象提取出来
  • json.loads() 将json字符串编码成Python对象
测试

json.dumps json 对象--->str

import json

def run1():
    # 定义一个json对象
    a = {"name": "zhangsan", "age": 18}
    print(type(a))
    b = json.dumps(a)
    print(type(b))

if __name__ == '__main__':
    run1()
--------------输出------------
<class 'dict'>
<class 'str'>

json.dump json对象写入text.txt

def run2():
    try:
        file = "text.txt"
        a = {"name": "zhangsan", "age": 18}
        with open(file, 'w') as f:
            json.dump(a, f)
    except Exception as e:
        print(e)

当前目录下输出一个文件text.txt,内容如下

{"name": "zhangsan", "age": 18}

json.load json文件--> json对象

def run3():
    """
    text.txt --> json type
    :return:
    """
    try:
        file = "text.txt"
        with open(file, 'r') as f:
            return json.load(f)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    a = run3()
    print(type(a)) 
--------输出如下------------
<class 'dict'>

json.loads() json字符串--> json对象

def run4():
    # 定义一个json字符串
    a = """{"name": "zhangsan", "age": 18}"""
    print(type(a))
    b = json.loads(a)
    print(type(b))
------输出如下-----
<class 'str'>
<class 'dict'>

总结

在本次编码中,需求是将构建好的Json对象返回,最终写入文件,所以选择json.dump()

代码如下:

    def output_file(self, data, fun):
        try:
            logfile = self.outFilePath + "_" + fun + '.result'
            print("function output file:" + logfile)
            with open(logfile, 'w') as f:
                json.dump(data, f)
        except Exception as e:
            logging.error("ouput to file error" + str(e))

data: json对象

logfile: 当前路径下的输出文件名称

执行 hdfs_config.py 最终输出如下:

-rw-r--r--. 1 root root    99 10月 27 12:56 hdfs_install_task_checkHDFSGroup.result
-rw-r--r--. 1 root root    99 10月 27 12:56 hdfs_install_task_checkHDFSUser.result
-rw-r--r--. 1 root root   238 10月 27 12:56 hdfs_install_task_chown2Hadoop.result
-rw-r--r--. 1 root root 53512 10月 27 12:56 hdfs_install_task_decompressionHDFS.result
-rw-r--r--. 1 root root   123 10月 27 12:56 hdfs_install_task_lnsHDFSConfig.result
-rw-r--r--. 1 root root   223 10月 27 12:56 hdfs_install_task_makeHDFSDir.result
-rw-r--r--. 1 root root   100 10月 20 11:30 checkWebUI.py
-rw-r--r--. 1 root root   747 10月 25 11:56 datanode.py
-rw-r--r--. 1 root root 23344 10月 27 12:55 hdfs_config.py  ## 执行脚本
-rw-r--r--. 1 root root 24886 10月 27 12:41 hdfs_install_task

内容:

{"exit_code": 0, "exec_cmd": "ln -s /srv/dstore/1.0.0.0/hdfs/etc /etc/dstore/1.0.0.0/hdfs", "message": "ln -s is success!"}

标签:hdfs,10,Python,json,--,JSON,--.,解析,root
From: https://www.cnblogs.com/nwnusun/p/16832213.html

相关文章

  • 【js】json的相关操作
    1、将json数据和数组融合demo<script>varjson={all:10,un:3,comp:2,inc:5}......
  • Python在接口测试中的应用
    1.介绍接口测试的方式有很多,可以使用的工具有jmeter,postman,soapUI等,也可以自己写代码进行接口测试(Python,java,go等等),工具的使用相对来说都比较简单,开箱即用。但如果接口中定......
  • 一文带你了解 Python 中的继承知识点
    1类继承Python是面向对象的编程语言,因此支持面向对象的三大特性之一:继承。继承是代码重用的一种途径,Python中的继承就像现实生活中的继承一样,子类可以顺利继承父类的属性......
  • Python7-实战
    实战01(修改手机默认语言)1classPhone:2'''手机类'''3def__init__(self,language='英文'):4iflanguage=='英文':5print("智能手......
  • conda管理python环境
    Anaconda使用教程Anaconda详细安装使用教程condacreate-nlearnpython=3//创建一个名为learn的环境并指定python版本为3(最新版本)condaactivatelearn//激活l......
  • postman 模拟json发送数据
    https://www.onlinedown.net/article/10021411.htm  在地址栏里输入请求:127.0.0.1:8081/getmoney      选择“POST”方式。      在“headers”添加ke......
  • python遇到IndexError: only integers, slices (`:`), ellipsis (`...`)……
    完整错误信息如下:IndexError:onlyintegers,slices(​​:​​​),ellipsis(​​...​​​),numpy.newaxis(​​None​​)andintegerorbooleanarraysarevalid......
  • python获取文件夹、文件大小&hiberfil.sys
    跑了个很简单的程序,c盘突然爆炸增加,顿时SSD120G的盘只剩下几个G,所以有需求看看那些文件占用了大量空间。(事先通过360大文件扫描、日期排序分析未发现异常)importosimportsy......
  • python的开源微信接口
    开源微信接口文档地址:​​https://itchat.readthedocs.io/zh/latest/​​​github地址:​​​https://github.com/littlecodersh/itchat​​如下举例:importitchatitchat.......
  • OpenCV-Python learning-13.人脸检测
    如下,调用opencv使用摄像头或视频进行人脸检测,也可以在函数​​recognize(img)​​​传入​​img=cv2.imread('face.jpg')​​​。其中,人脸级联分类器xml文件我引用的是anaco......