分享

使用Python附加到JSON文件

 软件测试test 2020-06-30

JSON的完整形式是JavaScript Object Notation。这意味着将使用编程语言的文本组成的脚本(可执行)文件用于存储和传输数据。Python通过名为的内置包支持JSON json要使用此功能,我们以Python脚本导入json包。JSON中的文本是通过带引号的字符串完成的,该字符串包含中的键-值映射中的值{ }

使用的功能:

  • json.loads(): python内置的“ json”模块中提供json.loads()函数。此函数用于解析JSON字符串。

语法:json.loads(json_string)
参数:以JSON字符串为参数。
返回类型:返回python字典对象。

  • json.dumps(): python内置的“ json”模块中提供了json.dumps()函数。此函数用于将Python对象转换为JSON字符串。

语法:json.dumps(对象)
参数:以Python对象为参数。
返回类型:返回JSON字符串。
  • update():此方法使用来自另一个字典对象或可迭代键/值对的元素更新字典。

语法:dict.update[other]
参数:采用另一个数字或可迭代的键/值对。
返回类型:返回无。

示例1:更新json字符串。

# Python program to update # JSON import json # JSON data: x = '{ "organization":"GeeksForGeeks", "city":"Noida", "country":"India"}' # python object to be appended y = {"pin":110096} # parsing JSON string: z = json.loads(x) # appending the data z.update(y) # the result is a JSON string: print(json.dumps(z))

输出:

{“ pin”:110096,“ organization”:“ GeeksForGeeks”,“ country”:“ India”,“ city”:“ Noida”}

示例2:更新JSON文件。假设json文件如下所示。

我们要在emp_details之后添加另一个json数据。下面是实现。

# Python program to update # JSON import json # function to add to JSON def write_json(data, filename='data.json'): with open(filename,'w') as f: json.dump(data, f, indent=4) with open('data.json') as json_file: data = json.load(json_file) temp = data['emp_details'] # python object to be appended y = {"emp_name":'Nikhil', "email": "nikhil@geeksforgeeks.org", "job_profile": "Full Time" } # appending data to emp_details temp.append(y) write_json(data)

输出:

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多