当前位置: 首页 > news >正文

Python3操作Json文件碰到的几个问题

文章目录

  • 小结
  • 问题及解决
    • byte数组与str字符串之间不兼容
    • 没有Index属性
    • JSON.DUMP(S) & JSON.LOAD(S)
  • 参考

小结

使用Python3操作Json文件碰到的几个问题,进行了解决。

问题及解决

byte数组与str字符串之间不兼容

以下的几个问题都是由于字节数组和字符串之间类型不匹配导致的问题:

  • TypeError: can’t concat str to bytes

  • TypeError: keys must be str, int, float, bool or None, not bytes

  • TypeError: a bytes-like object is required, not ‘str’

  • Invalid type for parameter LoadBalancerArn, value: b’arn:aws:elasticloadbalancing:ap-southeast-1:123456789012:loadbalancer/app/spring-petclinic-rest-elb/8616ff3572df2ed3’, type: <class ‘bytes’>, valid types: <class ‘str’>

一般由以下几个办法解决:

  • 如果是byte数组,需要转化为字符串,尝试使用以下办法byte_array_to_convert.decode("utf-8") 或者 str(byte_array_to_convert.decode("utf-8"))

  • 如果是字符串,想要转换为byte数组,尝试使用以下办法str_convert_to_byte_array.encode('utf-8')

没有Index属性

错误如下:

  • AttributeError: ‘dict_keys’ object has no attribute ‘index’

解决办法,实际上是把这个变量转化为list类型,例如:

Name=project_name + str(list(service_list.keys()).index(service)) + '-tg'

JSON.DUMP(S) & JSON.LOAD(S)

以下是一个示例:

#!/bin/python
import jsonhome = expanduser("~")
filename = home + '/.docker/config.json'
with open(filename, 'r+') as f:data = json.load(f)data["auths"] = {hostname.decode("utf-8"): {"auth": ecr_login_token.decode("utf-8")}}f.seek(0)f.write(json.dumps(data, indent=4))f.truncate()

其中indent=4是对Json文件进行美化。

参考

stackoverflow: json.dump() gives me “TypeError: keys must be a string”
JSON.DUMP(S) & JSON.LOAD(S)
Python.org: json — JSON encoder and decoder
stackoverflow: Convert bytes to a string in Python 3
Python JSON Pretty Print | Guide (With Examples)
stackoverflow: “TypeError: a bytes-like object is required, not ‘str’” when handling file content in Python 3
stackoverflow: AttributeError: ‘dict_values’ object has no attribute ‘index’

http://www.lryc.cn/news/271395.html

相关文章:

  • Java中的自定义异常处理:业务异常类的创建与使用
  • 微信小程序有几个文件
  • 计算机网络:知识回顾
  • 【Python百宝箱】音韵探奇:探索Python中的音频与信号魔法
  • springboot(ssm农产品直卖平台 农产品商城系统Java系统
  • C#编程-使用条件构造
  • 【BERT】深入理解BERT模型1——模型整体架构介绍
  • 【Java开发岗面试】八股文—设计模式
  • GO基础进阶篇 (九)、临界资源安全问题(锁、channel)
  • Python基础-04(比较运算符、逻辑运算符)
  • MySQL 四种插入命令及其特点与锁机制
  • AKShare学习笔记
  • A星寻路算法
  • QDialog
  • Spark中使用DataFrame进行数据转换和操作
  • windows11新装机,简单评测系统自带软件(基本涵盖日常所需应用)
  • 概念解析 | Shapley值及其在深度学习中的应用
  • ajax的完整写法——success/error/complete+then/catch/done+设置请求头两种方法——基础积累
  • 《Linux详解:深入探讨计算机基础》
  • HarmonyOS 实践之应用状态变量共享
  • ThreadLocal共享变量
  • 前端crypto-js 库: MD5
  • 2024新年快乐
  • OpenCV-Python(21):轮廓特征及周长、面积凸包检测和形状近似
  • 连接progressql报错Cannot load JDBC driver class ‘org.postgresql.Driver‘,亲测有效!!!
  • SQLAlchemy快速入门
  • java 纯代码导出pdf合并单元格
  • Linux自己的应用商店yum
  • 集成电路模拟设计——【基于Serdes 应用的 串化/解串器 时钟与数据恢复电路CDR】
  • OpenWrt 编译入门(小白版)