从文件中删除特定的JSON对象,然后存储此文件

时间:2015-09-21 12:06:52

标签: python json boto

这只是我的json文件的一部分,如下所示:

sqs = boto.sqs.connect_to_region("ap-west-1")
q = sqs.get_queue("deathvally")
m = q.read(visibility_timeout=15)
if m == None:
  print "No message!"
else:
  with open('download.json', 'w') as json_data:
    print m.get_body()
    json_data.write(m.get_body())
    json_data.close()

    # I want a logic here which can simply delete the specific json objects
    # Something like this is what i tried but didn't work...
    #    clean_data = json.load(json_data)   
    #    for element in clean_data:         ##
    #      del element['sshdsakey'] 
    #      json_data.write(clean_data)

我有一个下载此文件的Python scipt ..我想解析这个文件并删除一些对象,如“swapsize”,“sshdsakey”

CrudService

我基本上需要解析获取的json文件,然后删除特定对象,然后将这个新修改过的东西写在文件中。

3 个答案:

答案 0 :(得分:1)

您可以使用本地json模块中的loads来解析json。 然后使用del

从dict中删除元素
import json

keys_to_remove = ['sshdsakey', 'selinux']

json_str = '''{
    "network_lo": "127.0.0.0",
    "ec2_block_device_mapping_root": "/dev/sda1",
    "selinux": "false",
    "uptime_seconds": 127412,
    "ec2_reservation_id": "r-cd786568",
    "sshdsakey": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
}'''

data = json.loads(json_str)
for key in keys_to_remove:
    if key in data:
        del data[key]
print data

答案 1 :(得分:1)

json.loads会将JSON字符串解码为Python字典(虽然您提供的格式不是有效的JSON格式,但每边都必须有花括号),然后您可以使用{{1}删除所需的键。使用del将字典编码回JSON字符串并写入resultit

json.dumps

答案 2 :(得分:0)

您需要先将JSON对象字符串转换为Python dict,从中删除密钥,然后写入输出文件。

import json

sqs = boto.sqs.connect_to_region("ap-west-1")
q = sqs.get_queue("deathvally")
m = q.read(visibility_timeout=15)
if m is None:
    print "No message!"
else:
    KEYS_TO_REMOVE = "swapsize", "sshdsakey", "etc"

    with open('download.json', 'w') as json_data:
        json_obj = json.loads(m.get_body())
        for key in KEYS_TO_REMOVE:
            try:
                del json_obj[key]
            except KeyError:
                pass
        json_data.write(json.dumps(json_obj, indent=4))