Konstantin Rusanov
Konstantin Rusanov

Reputation: 6554

Parse JSON find value and append random number?

I have a JSON file with login and integer valuer (some result), like this:

[
        {
           "name":"Tamara",
           "results":"434.545.234.664"
        },
        {
           "name":"Ted",
           "results":"434.545.234.664"
        }
]

I need to receive user login (name), find inserted name in JSON. If it already exists, add some number to the "results".

For example: If I input "Ted", some number will be appended to Ted's results like this: "results":"434.545.234.664+4343}"

If name doesn't exist, add new record with:

{
    "name":"new_name",
    "results":"some_number"
}

in it.

My code, which didn't work:

with open('/Users/users_db.json') as jsonfile:
    user_name = ''
    while user_name == '':
        data = json.load(jsonfile)
        user_name = input('Your name: ')
        for user in data:
            if user_name in user['name']:
                print('Old user')
                break
            else:
                print('New user')

Upvotes: 0

Views: 770

Answers (2)

BPL
BPL

Reputation: 9863

Here's one of the zillion possible ways to code your problem:

import json
import random
import names

random.seed(1)

data = [
    {
        "name": "Tamara",
        "results": "434.545.234.664"
    },
    {
        "name": "Ted",
        "results": "434.545.234.664"
    }
]


def foo(lst, name):
    some_number = random.randint(0, 4343)
    values = filter(lambda d: d["name"] == name, lst)

    if values:
        for v in values:
            v["results"] += "+{0}".format(some_number)
    else:
        lst.append({
            "name": name,
            "results": some_number
        })

for name in ["Tamara", "Ted"] + [names.get_first_name() for i in range(8)]:
    foo(data, name)

print(data)

This one will use names module to generate random test names.

One advice though, take some time to read the help page, especially the sections named "What topics can I ask about here?" and "What types of questions should I avoid asking?". And more importantly, please read the Stack Overflow question checklist. You might also want to learn about Minimal, Complete, and Verifiable Examples

Upvotes: 1

Daniel Kravetz Malabud
Daniel Kravetz Malabud

Reputation: 783

You can parse your json like this

import json

with open('yourJsonFile.json') as example_data:
    data = json.load(example_data)

And now it's a matter of working with data to find whatever you need. For example, to access the first name you could do

data[0]['name']

The rest depends on where/how you store the names and check if they already exist.

Finally, to add a new value you can use append

Upvotes: 0

Related Questions