如何在python中将元素添加到空JSON? [英] How to add an element to an empty JSON in python?

查看:553
本文介绍了如何在python中将元素添加到空JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个空字符串&通过json.dump将其转换为JSON.一旦我要添加元素,它就会失败&显示

I created an empty string & convert it into a JSON by json.dump. Once I want to add element, it fails & show

AttributeError:'str'对象没有属性'append'

AttributeError: 'str' object has no attribute 'append'

我同时尝试了json.insert& json.append,但它们都不起作用.

I tried both json.insert & json.append but neither of them works.

似乎是数据类型问题.由于Python无法将数据类型声明为Java& C可以,如何避免这个问题?

It seems that it's data type problem. As Python can't declare data type as Java & C can, how can I avoid the problem?

import json

data = {}
json_data = json.dumps(data)
json_data.append(["A"]["1"])
print (json_data)

推荐答案

JSON是数据的字符串表示形式,例如列表和字典.您无需附加到JSON,而是附加到原始数据,然后将其转储.

JSON is a string representation of data, such as lists and dictionaries. You don't append to the JSON, you append to the original data and then dump it.

此外,您不将append()与字典一起使用,而是将其与列表一起使用.

Also, you don't use append() with dictionaries, it's used with lists.

data = {} # This is a dictionary
data["a"] = "1"; # Add an item to the dictionary
json_data = json.dumps(data) # Convert the dictionary to a JSON string
print(json_data)

这篇关于如何在python中将元素添加到空JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆