1

I have the following structure in my JSON:

{
    "function": "ComAl_Set_nad_crtl_xcall_state",
    "timeStamp": 1488516897797,
    "Param1": "SIG_NAD_CRTL_XCALL_STATE",
    "Value1": "8"
},
{
    "function": "ComAl_Set_nad_crtl_xcall_state",
    "timeStamp": 1488516912217,
    "Param1": "SIG_NAD_CRTL_XCALL_STATE",
    "Value1": "10"
},

I create this json by getting using the following method:

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

So far I only needed the last value1 from the JSON, which I am getting like this:

def get_last_element(self, json_stub, value='Value1'):
    last_element_from_json = json_stub[-1].get(value)
    if len(json_stub) > 0 and last_element_from_json is not None:
        return last_element_from_json
    else:
        pass

my question is can I get the previous value1 as well (for example in my JSON value1: 8 and value1: 10) because for now, I get this value using json_stub[-1] which will always give me the last value? thanks.

1 Answer 1

2

Use -2 to get the second from last.

json_stub[-2] 

In Python negative index points to an element from right-to-left of the list as opposed to the default left-to-right. -1 for the the last element (left-to-right), -2 for the second from last (left-to-right) etc.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.