Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting last element from a JSON with Python

Tags:

python

json

I have files with the following structure:

{
    "function": "ComAl_Set_nad_crtl_xcall_state",
    "timeStamp": 1488500329974,
    "Param1": "SIG_NAD_XCALL_ATTEMPTS_COUNT",
    "Value1": "2"
}

These JSON files are created by some functions which I have in my program. But I have an issue getting the last value from these files (Value1). Currently this is the code I am using to get data from the file:

def get_json_from_stub(self, file_name):
    def jsonize_stub(raw_data):
        end = raw_data.rfind(",")
        parsed_data = "[" + raw_data[:end] + "]" 
        return json.loads(parsed_data.replace("\00", ""))

    command = "'cat "  + self.stub_path + file_name + "'"
    content =  self.send_ssh_command(command)
    json_stub = jsonize_stub(content)
    return json_stub

and this is the code for getting Value1:

@app.route('/stub/comal/getSignal/ComAl_Set_nad_crtl_xcall_requests', methods=['GET'])
    def get_nad_crtl_xcall_requests():
        file_name = "ComAl_Set_nad_crtl_xcall_requests.out"
        json_stub = self.stubManager.get_json_from_stub(file_name)
        return MapEcallRequests().tech_to_business(json_stub[-1]["Value1"])

more specifically I want to replace json_stub[-1]["Value1"] with another way of getting Value1. The problem is that sometimes these files don´t get written so I would like to get Value1 in a different way and to raise an error message in case Value1 isn´t there, just to avoid my application crashing in case the value is not there. Is there are way to do it? Thanks.

like image 730
H.A. Avatar asked Mar 22 '26 13:03

H.A.


1 Answers

You can check if the key exists (you can also check if the length is correct):

if len(json_stub) > 0 and json_stub[-1].get('Value1') is not None:
    value1_node = json_stub[-1]('Value1')
else:
    # 'Value1' key does not exist  
like image 87
Surcle Avatar answered Mar 24 '26 22:03

Surcle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!