2

One of my responses looks like,

{
    "password": [
        "Ensure that this field has atleast 5 and atmost 50 characters"
    ]
}

And I am trying to fetch the string inside password.How I can get it.

Below is the code which I am trying

key = json.loads(response['password'])
print(key[0]),

But it says 'string indices must be integers, not str'

4
  • 2
    is this in python? Commented Sep 5, 2019 at 5:42
  • 1
    In java or ???? Commented Sep 5, 2019 at 5:42
  • 1
    I am trying in python Commented Sep 5, 2019 at 5:44
  • 2
    Please provide the script language in the tags to help you with your problem .. Commented Sep 5, 2019 at 5:45

2 Answers 2

5

The error message is correct.

key = json.loads(response['password'])
print(key[0]),

The format of json is string. You need to convert the string of a json object to python dict before you can access it.

i.e.: loads(string) before info[key]

key = json.loads(response)['password']
print(key[0])
Sign up to request clarification or add additional context in comments.

Comments

1

Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).

so assuming your response is actually a string (eg that was retrieved from a HTTP request/endpoint) then you deserialise it with json.loads (the function is basically load from string), then you've got a map with a 'password' key, that is an array, so grab the first element from it.

import json

resp = '{ "password": [ "Ensure that this field has atleast 5 and atmost 50 characters" ] }'
print json.loads(resp)['password'][0]

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.