简体   繁体   中英

Select Specific Fields From JSON File - Python

Im trying to compare two json files. One is a json.dump and the other is a new json object coming into the method.

We generate a JSON file using results of tests from a server, they are then passed into this method:

def save_json_results(data):
    if not os.listdir('/opt/Code/JSON'):
        with open('/opt/Code/JSON/current_json.json','w') as outfile:
        json.dump(data,outfile)
        send_json_results(data)
    else:
        f = open('/opt/Code/JSON/current_json.json')
        file_data = json.loads(f)
        d = json.loads(data)
        if sorted(file_data.items()) == sorted(d.items()) and file_data.get("timestamp",{}) != d.get("timestamp",{}):
            with open('/opt/Code/JSON/current_json.json','w') as outfile:
                json.dump(data,outfile)
        else:
            os.rename('/opt/Code/JSON/current_json.json','/opt/cfm_health_checks/Code/JSON/prev_json.json')
            with open('/opt/Code/JSON/current_json.json','w') as outfile:
                json.dump(data,outfile)
            send_json_results(data)

The premise of this method is to take the JSON object which is being passed in (data) and then check a directory if it is empty then store this file as the most up to date JSON, else it will attempt to open the file which is already there (I might be wrong in assuming I have to reload it as a JSON object) then try and compare the files, if they are the same and its only the timestamp which is different then dont send the JSON onto the database (as it is just wasting network resources as no information about the test results are different) however it will still make the new data = the most current JSON, else it will send it to the database and rename the files accordingly.

{
"acronym": "", 
"api": [], 
"cell_version": "", 
"cfm": [], 
"city": "Belfast", 
"country": "UK", 
"latitude": 54.614443, 
"longitude": -5.899953, 
"nas": [], 
"node": [], 
"number_of_cells": "", 
"switch": [], 
"timestamp": "2015-01-19 15:04:13.489097"
}

Example JSON above.

The d and file_data objects returned by json.loads should have the standard python dictionary interface.

Therefore you should be able to access the acronym value in d using d["acronym"] .

You could also do for keyvaluepair in file_data.items(): to iterate through each JSON entry and apply a separate comparison to each key value pair based on the key name.

You could also do [d[k[0]] for k in sorted(d.items()) if k[0] != "timestamp"] == [file_data[k[0]] for k in sorted(file_data.items()) if k[0] != "timestamp"] Although that's a very long line, and I wouldn't personally let that past a code review.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM