2017-11-27 1 views
0

그래서 JSON 객체로 저장하려는 출력이 작은 스크립트가 있습니다. 다음은 스크립트입니다.별도의 JSON 대신 중첩 된 JSON을 생성했습니다.

import dns.resolver 
import json 

def get(domain): 
    ids = [ 
     'CNAME', 
     'A', 
     'NS', 
    ] 

    for _iter in ids: 
     try: 
      inf = dns.resolver.query(domain, _iter) 
      response_dict["Domain"] = domain 

      for _resp in inf: 
       print(_iter, ':', _resp.to_text()) 
       response_dict[_iter] = _resp.to_text() 

     except Exception as e: 
      print(e) 

    # dump information as a JSON file. 'a' to append file. 
    with open('data.txt', 'a') as outfile: 
     json.dump(response_dict, outfile) 

    print(response_dict)   


if __name__ == "__main__": 
    response_dict = dict() 
    get("apple.com") 
    get("google.com") 

이제 출력 결과는 JSON에서 별도의 개체를 생성합니다.

{"Domain": "apple.com", "A": "17.178.96.59", "NS": "b.ns.apple.com."} 
{"Domain": "google.com", "A": "172.217.21.238", "NS": "ns3.google.com."} 

내가 실제로 할 수 있습니다 :

JSON

는 어떻게 달성 할 수 있는가? 감사!

답변

2

get()을 호출 할 때마다 파일에 추가하는 대신 결과를 목록에 추가하고 끝에 덤프하십시오. __main__response_dict을 정의하지 마십시오.

import dns.resolver 
import json 

def get(domain): 
    ids = [ 
     'CNAME', 
     'A', 
     'NS', 
    ] 

    response_dict = {} 
    for _iter in ids: 
     try: 
      inf = dns.resolver.query(domain, _iter) 
      response_dict["Domain"] = domain 

      for _resp in inf: 
       print(_iter, ':', _resp.to_text()) 
       response_dict[_iter] = _resp.to_text() 

     except Exception as e: 
      print(e) 

    print(response_dict) 
    return response_dict # return a value 


if __name__ == "__main__": 
    response_list = [] 
    # append each output of get() to this list 
    response_list.append(get("apple.com")) 
    response_list.append(get("google.com")) 

    # write the list to a file 
    with open('data.txt', 'a') as outfile: 
     json.dump(response_list, outfile) 
+0

고마워요! 최대한 빨리 답변을 드리겠습니다. –