问题:有1个文件t1.txt数据格式是json。

有另外1个文件t2.txt是key1111,key2222。把对应在t1.txt中的值删掉,有什么好办法么?

思路1:1条shell命令

cat t1.txt | python -c 'import sys,json; a=json.load(sys.stdin);del a["jobs"]["1111"];del a["jobs"]["2222"];print a'
cat t1.txt | python -m json.tool >> t2.txt
sed '/1111\|2222/,+3d' t2.txt

 

思路2:用python脚本删,把t1赋给1个字典型的变量,把t2给一个list变量,循环读取变量元素作为key,直接删除t1对应的值。
主要是string转换为dict或者json文件直接转换为dict。

1)# 使用json模块直接把文件转换为字典值
#https://docs.python.org/3/library/json.html

#!/usr/bin/env python
import json
def convertDict():
    with open('t1.txt') as json_file:
        data = json.load(json_file)
        return data
        
if __name__ == "__main__":
    fileToDict = convertDict()
    keyList = ["key1111","key2222"]
    for k in keyList:
        del fileToDict["jobs"][k]
    print json.dumps(fileToDict)

 

2)# 因为这是个linux下的配置文件,可以使用commands模块call shell command取值。
#http://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary
#convert string to dictionay by
#ast.literal_eval or json.loads()

#!/usr/bin/env python
import commands
import json
def convertDict():
    outStr = commands.getoutput("cat t1.txt  | python -m json.tool")
    json_acceptable_string = outStr.replace("'", "\"")
    toDict = json.loads(json_acceptable_string)
    print type(toDict)
    print toDict
    return toDict

if __name__ == "__main__":
    fileToDict = convertDict()
    keyList = ["1111","2222"]
    for k in keyList:
        del fileToDict["jobs"][k]

    print json.dumps(toDict)

 

3)# other ways for convert string to dictionay

#http://leaya00.iteye.com/blog/853366

#!/usr/bin/env python
import commands
import json
def convertDict():
    outStr = commands.getoutput("cat t1.txt | python -m json.tool")
    toDict = eval(outStr)
    #exec("toDict=" + outStr)
    print type(toDict)
    print toDict
    return toDict
if __name__ == "__main__":
    fileToDict = convertDict()
    keyList = ["1111","2222"]
    for k in keyList:
        del fileToDict["jobs"][k]
    print json.dumps(fileToDict)

4)遇到的错误TypeError: string indices must be integers, not str
http://stackoverflow.com/questions/15388980/typeerror-string-indices-must-be-integers-not-str
主要是使用commands.getoutput()获取shell命令的输出值是个string,不能直接当作dict来处理。

5)一些基础的python知识参考
http://www.runoob.com/python/python-dictionary.html
http://www.jb51.net/article/47978.htm list
http://www.jb51.net/article/47990.htm dictionary
https://docs.python.org/3/library/json.html

posted on 2017-02-14 17:49  维也纳下午茶  阅读(21635)  评论(0编辑  收藏  举报