0

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.

Vikram Ranabhatt
  • 7,268
  • 15
  • 70
  • 133
  • .get with defaults / defaultdict ? https://stackoverflow.com/questions/43491287/elegant-way-to-check-if-a-nested-key-exists-in-a-python-dict/43491315#43491315 , https://stackoverflow.com/questions/9358983/dictionaries-and-default-values – QHarr May 10 '19 at 05:47
  • What's the response `Content-Type`? – Tomalak May 10 '19 at 07:02
  • This is invalid json, so the real solution is to contact the API maintainers and report the bug. – bruno desthuilliers May 10 '19 at 07:28

1 Answers1

1
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.

user448518
  • 76
  • 5
  • Relying on the exception's message is brittle at best. Then, the `else` block should actually re-raise the original exception (so you have the full error message AND traceback) instead of printing it. And finally, you should use a `while` loop here. Oh and yes: in python2, this would raise a ValueError, not a json.JSONDecodeError, and the error message is different... – bruno desthuilliers May 10 '19 at 07:26
  • I tried this but JSONDecodeError is not supported in 2.7.6 ? – Vikram Ranabhatt May 10 '19 at 11:11