2016-12-09 11 views
0

私は、ファイルと出力の違いを調べようとしています。誰かが私をどのようにして新しいjsonファイルに書き込むことができるかについて助けてくれたら は、ここに私のコードpython - ifとelifからの出力をjsonファイルに書き込む

私は、コンソール上のJSONファイルの代わりに、印刷への出力を書きたいと思い
def check(a,b): 
    diff = False 
    for a_key in a: 
     if a_key not in b: 
      diff = True 
      #print "key %s in a, but not in b" %a_key 
      print a_key,a[a_key] 
     elif a[a_key] != b[a_key]: 
      diff = True 
      #print "key %s in a and in b, but values differ (%s in a and %s in b)" %(a_key, a[a_key], b[a_key]) 
      print a_key,b[a_key] 
    if not diff: 
     print "both files are identical" 

です。 私は印刷後にこれを試しましたが、o/pを望んでいませんでした。どんな助けもありがとうございます。

res=a_key,b[a_key] 
out_file = open("out.json","a") 
json.dump(res,out_file, indent=4) 
out_file.close() 

ここにサンプルファイルがあります。 FILE1:

{ 
"abc": [ 
    "build=1.0.44.0", 
    "proxy=none" 
], 
"xyz": [ 
    "proxy=none", 
    "build=1.0.129.0" 
], 
"lmn": [ 
    "build=1.0.127.0", 
    "proxy=none" 
], 
"test": [ 
    "build=1.0.144.0", 
    "proxy=http" 
], 
"alfa": [ 
    "build=1.0.22.0", 
    "proxy=http" 
], 
"beta": [ 
    "proxy=http", 
    "build=1.0.17.0" 
] 
} 

ここではFile2のです:

{ 
"abc": [ 
    "build=1.0.43.0", 
    "proxy=none" 
], 
"xyz": [ 
    "proxy=none", 
    "build=1.0.128.0" 
], 
"lmn": [ 
    "build=1.0.127.0", 
    "proxy=none" 
], 
"test": [ 
    "build=1.0.141.0", 
    "proxy=http" 
], 
"alfa": [], 
"beta": [ 
    "proxy=http", 
    "build=1.0.17.0" 
] 
} 

FINAL予想される出力:

{ 
"abc": "1.0.44.0", 
"xyz": "1.0.129.0", 
"test":"1.0.144.0", 
"alfa":"1.0.22.0" 
} 
+1

ためexpeted出力は何ですかマット – Backtrack

+0

希望する出力は何ですか? –

+0

@Backtrack私はちょうど所望の出力を更新しました – ryan1506

答えて

0
A = {"abc":["build=1.0.44.0","proxy=none"],"xyz":["proxy=none","build=1.0.129.0"],"lmn":["build=1.0.127.0","proxy=none"],"test":["build=1.0.144.0","proxy=http"],"alfa":["build=1.0.22.0","proxy=http"],"beta":["proxy=http","build=1.0.17.0"]} 

B = {"abc":["build=1.0.43.0","proxy=none"],"xyz":["proxy=none","build=1.0.128.0"],"lmn":["build=1.0.127.0","proxy=none"],"test":["build=1.0.141.0","proxy=http"],"alfa":[],"beta":["proxy=http","build=1.0.17.0"]} 


import json 
def check(a,b): 
    diff = False 

    output = {} 

    for a_key in a: 
      if a_key not in b: 
       diff = True 
       output[a_key] = a[a_key][0] 
      elif a[a_key] != b[a_key]: 
       diff = True 
       for v in a[a_key]: 
        if 'build=' in v: 
         output[a_key] = v.replace('build=','') 
    if not diff: 
      print ("both files are identical") 
    else: 
     print(output) 
     with open("output.json","w") as outfile: 
      outfile.write(json.dumps(output)) 


check(A,B) 

出力に含ま:

{"xyz": "1.0.129.0", "alfa": "1.0.22.0", "abc": "1.0.44.0", "test": "1.0.144.0"} 
関連する問題