1

I have the following JSON data the I need to read in Flask:

{
"NewList":[
    {
        "key" : "myvalue1",
        "value" : "value1"
    },
    {
        "key" : "myvalue2",
        "value" : "value2"
    },
    {
        "key" : "myvalu3",
        "value" : "value4"
    }
]
}

And I'm having trouble doing so. The code I currently have is as follows:

@app.route('/dataread', methods=['GET', 'POST'])
def dataread():
    if(request.json):
            myvalue1 = request.json['NewList']['myvalue1']
            return str(myvalue1)
        else:
            return 'nothing'

But it isn't working. I'm getting the following error:

KeyError: 'NewList'

I know my syntax must be wrong but I can't figure how to fix it. I'm sorry for such a newb question. Please can you help.

Thanks.

7
  • myvalue1 is not a valid key. Dictionaries can be indexed by keys, not by their values. Commented Jul 4, 2017 at 15:37
  • 3
    What do you see if you print request.json? Might reveal a structuring issue. Additionally, "myvalue1" is not a key in this dictionary, despite what you've named it in the original. Commented Jul 4, 2017 at 15:37
  • 1
    Additionally, "NewList" represents a list not a dictionary, so trying to get items from it with keys is not going to work. Commented Jul 4, 2017 at 15:40
  • 1
    @JackParkinson Thanks for pointing that out. Commented Jul 4, 2017 at 15:40
  • 1
    Why create a list of dicts in "NewList" ? Rather it can be handled as dict of dicts like {"NewList": { "key1": "value1", "key2": "value2", ..}}. Then access this using request.json['NewList']['key1'] where key1 could be 'myvalue1' w.r.t your code Commented Jul 4, 2017 at 15:45

3 Answers 3

2

There's a few things going in your example that aren't correct. The json is actually interpreted as :

{ "NewList":[
    {
        "key1" : "value1",
        "key2" : "value2"
    },
    {
        "key1" : "value1",
        "key2" : "value2"
    }
]}

So in your example myvalue1 is a value not a key.

The main error however is that in flask request.json() only returns the whole json input, you can't select certain elements from the json. Also request.json is deprecated so it now should be request.get_json()

So the final solution given your input data would be something like

{
"NewList":[
    {
        "key" : "myvalue1",
        "value" : "value1"
    },
    {
        "key" : "myvalue2",
        "value" : "value2"
    },
    {
        "key" : "myvalu3",
        "value" : "value4"
    }
]
}


@app.route('/dataread', methods=['GET', 'POST'])
def dataread():
    if(request.data):
            jdata = request.get_json()
            return str(jdata['Newlist'][0]['key'])
        else:
            return 'nothing'

The [0] being the first object in the array that's the value of Newlist. Unless you know it's always going to be array element 0 you'll get dud data, plus you're returning the value of the "key". Given that input data I suspect you probably want something more like.

if(request.data):
    jdata = request.get_json()
    for j in jdata['Newlist']:
        if j['key'] == 'myvalue1':
            return str(j['value'])

    return 'not found'
else:
    return 'nothing'
Sign up to request clarification or add additional context in comments.

Comments

1

I wasn't sure which part of this you were having an issue with so I did it long hand. It's obviously not ideal but should be easily understandable.But I would echo the comment above that you should start by printing exactly what you got in. May not be a complete match.

The dictionary is a set of lists of dictionaries so you end up walking the set for each one.

dict = {
"NewList":[
    {
        "key" : "myvalue1",
        "value" : "value1"
    },
    {
        "key" : "myvalue2",
        "value" : "value2"
    },
    {
        "key" : "myvalu3",
        "value" : "value4"
    }
]
}

for firstkey, big_list in dict.items():
    print('print dict: ' + str(firstkey))
    for pair in big_list:
        print('print sets in dict: ' + str(pair))
        nextdict = pair
        for nextkey, small_list in nextdict.items():
            print('print each: ' + str(nextkey)+ '->' + str(small_list))
            #address each one
            print('pull just data: ' + str(nextdict[nextkey]))


"""
results
print dict: NewList
print sets in dict: {'key': 'myvalue1', 'value': 'value1'}
print each: key->myvalue1
pull just data: myvalue1
print each: value->value1
pull just data: value1
print sets in dict: {'key': 'myvalue2', 'value': 'value2'}
print each: key->myvalue2
pull just data: myvalue2
print each: value->value2
pull just data: value2
print sets in dict: {'key': 'myvalu3', 'value': 'value4'}
print each: key->myvalu3
pull just data: myvalu3
print each: value->value4
pull just data: value4
"""

Comments

0

The value of newList is a list. You have to access an element of this list first before reading off "key" and "value".

# print first item in the list
print(request.json['NewList'][0]['value']

# print them all
for item in request.json['NewList']
    print(item['key'])
    print(item['value'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.