Vikram Ranabhatt
Vikram Ranabhatt

Reputation: 7620

default value for missing value for a key in json in http output

I have situation where i get http response with missing value for a key.

import requests
http = requests.get(url, verify=False, auth=HTTPBasicAuth(self.username, self.password),
                                    timeout=self.timeout, headers=headers)

http.text gives output but http.json doesn't give any output.I understand that this issue is because of Invalid json format.

'{"PLMNID":[                 
               {  
                  "mNc":,
                  "id":3,
                  "mcc":
               },
               {  
                  "mNc":,
                  "id":4,
                  "mcc":
               },
               {  
                  "mNc":,
                  "id":5,
                  "mcc":
               },
               {  
                  "mNc":,
                  "id":6,
                  "mcc":
               }}'

Currently I retrun http.json.I see no response and also no error. Now i planning to return http.text output and some how add default value (may be '' or null)for missing key and proceed.

Do we have any python json api which will add default value for missing value for a key.

Upvotes: 0

Views: 1074

Answers (1)

user448518
user448518

Reputation: 76

import json
text = '{"sa": 1, "df":[{"vc":1,"mn":2},{"vc":1,"mn":}]}'
len_text = len(text)
j = 0
js = None

while j <= len_text:
    try:
        js = json.loads(text)
    except json.JSONDecodeError as mn :
        if mn.msg == "Expecting value":
            text1 = list(text)
            text1.insert(mn.pos, 'null')
            text = "".join(text1)
        else:
            print("Got other error than Expecting value at pos:{0} with error:{1}".format(mn.pos, mn.msg))
            break
    j += 1

print(js)

This code is checking for JSON decode error and when "Expecting value" msg appears it fills with "null" value at the index of JSON text. This repeated until it fills the "null" value or breaks if some other error msg appears.

Upvotes: 1

Related Questions