0

I'm trying to get usernames from logs. The server outputs them as json. In the example below, I need all usernames. Nothing I've tried so far worked. Any help is appreciated.

logs = [
    "nt5510-clark\\clark63",
    {
        "guid": "A07BB2CD",
        "name": "srvfs01",
        "ips": [
            "10.10.1.210"
        ]
    },
    {
        "guid": "DB2A9C9E",
        "name": "nt5510-clark",
        "ips": [
            "10.6.100.40"
        ]
    },
    {
        "guid": "97F7AEEC",
        "name": "lapinf-msa",
        "ips": [
            "192.168.0.32"
        ]
    },
    "stephen.robertson",
    "christian",
    {
        "guid": "C888A5B2",
        "name": "nb-mcsorley",
        "ips": [
            ""
        ]
    }
]

username_list = [value for (key,value) in logs.items() if key in logs]

Output:

    username_list = [value for (key,value) in logs.items() if key in logs]
AttributeError: 'list' object has no attribute 'items'

Expected Output:

["nt5510-clark\\clark63","srvfs01","nt5510-clark","lapinf-msa","stephen.robertson","christian","nb-mcsorley"]
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 2
    So what have you tried? Have you looked up how to read json in python? Do you understand how to get items from a dictionary, etc? – Peter Apr 27 '23 at 15:57
  • 1
    Even if what you tried didn't work, please show that code and what errors you were getting with an [edit] – OneCricketeer Apr 27 '23 at 15:59
  • yes, I do understand. The problem is I don't know how to get the items from the dicts and single strings. In the items there, you have strings mixed with dicts, if that makes sense. And that's when it goes awry for me. – OverflowStack Apr 27 '23 at 15:59
  • Does this help? https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python – OneCricketeer Apr 27 '23 at 16:00
  • Your error is simply saying that `logs` is a list. Lists don't have `.items()` function. Only dicts do – OneCricketeer Apr 27 '23 at 16:02
  • 1
    Don't use list comprehension like this for mixed data types. I'd recommend handle it in a for loop and use `isinstance` to check for dicts. – Peter Apr 27 '23 at 16:02
  • @OneCricketeer, Yes, I get that. But then if I change it to a dict, I get the unhashable error. – OverflowStack Apr 27 '23 at 16:05
  • You don't need to change `logs`... You need to remove the call to `(key, value) in logs.items()` with `[... for item in logs]`. But as mentioned, don't use a list comprehension here – OneCricketeer Apr 27 '23 at 16:06

3 Answers3

2

You could do something like this:

import json
output = []
with open("path/to/example.json") as f:
    d = json.load(f)
    for x in d:
        if not isinstance(x,dict):
            output.append(x)
        else:
            output.append(x['name'])

print(output)
Thesh
  • 21
  • 4
2

Here's how you can extract the values from the field "name" in Python and handle the case where there is only a single object:

import json

json_data = '[ "nt5510-clark\\clark63", { "guid": "A07BB2CD", "name": "srvfs01", "ips": [ "10.10.1.210" ] }, { "guid": "DB2A9C9E", "name": "nt5510-clark", "ips": [ "10.6.100.40" ] }, { "guid": "97F7AEEC", "name": "lapinf-msa", "ips": [ "192.168.0.32" ] }, "stephen.robertson", "christian", { "guid": "C888A5B2", "name": "nb-mcsorley", "ips": [ "" ] } ]'

data = json.loads(json_data)

names = []

for item in data:
    if isinstance(item, dict) and "name" in item:
        names.append(item["name"])
    elif isinstance(item, str):
        names.append(item)

print(names)

This code first loads the JSON data using the json.loads() method and then iterates over each item in the list. If the item is a dictionary with a "name" key, the value of that key is added to the names list. If the item is a string, it is added directly to the names list. The resulting list of names is stored in the names variable and printed to the console.

Do mark my answer as correct if its answering your question. Thank you :)

Eric Yi
  • 48
  • 6
0

logs is a list, not a dictionary, so you don't use .items() to loop over it. Just use for item in logs. Use isinstance() to distinguish the username strings from dictionaries.

username_list = [item if isinstance(item, str) else item['name'] for item in logs]
Barmar
  • 741,623
  • 53
  • 500
  • 612