1

I have a json file that looks something like this:

{
"mAutomaticTestCompleted": true,
"mAutomaticTestList": [
  {
    "mName": "acceleratorEntity",
    "mTestStatus": true,
    "mX": 3.8043518,
    "mY": 8.114105,
    "mZ": -3.3895721
  },
  {
    "mName": "barometerEntity",
    "mTestStatus": false,
    "mValue": 0
  }]
}

There are actually lots of fields like mAutomaticTestlist, all of them are lists of objects that look just like that. I need to write a function that takes device_name and JSON itself as its arguments and returns the value of the mTestStatus field.

Here's my attempt:

def hasPassed(device_name, data):
    if isinstance(data, dict):
        for key, value in data.items():
            if not isinstance(value, dict) and not isinstance(value, list):
                if key == 'mName' and value == device_name:
                    return data['mTestStatus']
                else:
                    return hasPassed(device_name, value)
            elif isinstance(data, list):
                for element in data:
                    return hasPassed(device_name, element)

The problem with this function is that it doesn't go over the whole JSON object.


EDIT:

So I would like my function to work this way:

hasPassed('barometerEntity', json_obj) 

would return False cos that's the value of the 'mTestStatus' corresponding the device_name (which is barometerEntity in this case).

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Albert
  • 2,146
  • 10
  • 32
  • 54
  • Can you provide an example of what you expect your output to look like? – vielkind Jul 13 '18 at 12:17
  • How do the last three lines in your sample code work? – David Maze Jul 13 '18 at 12:17
  • 1
    Are you looking to re-invent the wheel, or are you unaware that there is a json parser part of the python standard library? https://docs.python.org/3.7/library/json.html And how to use it: https://stackoverflow.com/a/2835672/3402205 – Geoff Lentsch Jul 13 '18 at 12:18
  • @vealkind I've just done it. – Albert Jul 13 '18 at 12:22
  • @GeoffLentsch No, in my case there may be lots of devices in the json file, all I know about it is its name and the function should return whether its mTestStatus is `True` or `False`. It should be done automatically like in the example provided above. – Albert Jul 13 '18 at 12:25
  • To clarify, your parameter `data` is already a python object (dict)? In other words, you've already parsed the JSON? – glibdud Jul 13 '18 at 13:06

2 Answers2

1

You have wrong code formatting, should be:

def hasPassed(device_name, data):
    if isinstance(data, dict):
        if 'mName' in data and data['mName'] == device_name :
            return data['mTestStatus']
        else :
            for k in data :
                if hasPassed(device_name, data[k]) : return True
    if isinstance(data, list):
        for element in data:
            if hasPassed(device_name, element) : return True
    return False

Last 3 lines -- move to the left.

And there should be return in the end of the function, that returns when your data is not list and not dict -- otherwise your sunction will return None and may crash something.

>>> hasPassed( 'barometerEntity', a)
False
>>> hasPassed( 'acceleratorEntity', a)
True
>>> 
lenik
  • 23,228
  • 4
  • 34
  • 43
  • @Albert your `for key, value in data.items():` loop never goes beyond the first element, it just returns `hasPassed( 'something', true)`, because the first element is mAutomaticTestCompleted : true – lenik Jul 13 '18 at 12:40
  • Yeah, but have you tried running your code? I tryed copy-pasting it and it didn't work for me either. It just returns `None`... – Albert Jul 13 '18 at 13:00
  • @Albert please, try the latest version, works for me =) – lenik Jul 13 '18 at 13:00
  • Yeah it works now...I'm sorta in a mad rush so I made the stupid mistake...Thank you a lot, it does work as expected now! – Albert Jul 13 '18 at 13:04
-1

Try this:

import json

def hasPassed(device_name, data):

  test_list = json.loads(obj)["mAutomaticTestList"]

  for elt in test_list:
      if elt["mName"] == device_name: return elt["mTestStatus"]
zguesmi
  • 321
  • 1
  • 11
  • No, in my case there may be lots of devices in the json file, all I know about it is its name and the function should return whether its mTestStatus is True or False. It should be done automatically like in the example provided in the question. I definitely need recursion here, This is not the whole json file, I didn't post it here cos it's too big but there may be lots of fields like `mAutomaticTestList` – Albert Jul 13 '18 at 12:57
  • sorry but you should've provided a clearer json structure ! – zguesmi Jul 15 '18 at 13:35