0

Working on a small project that returns JSON on API call. However, I seem to be unable to obtain the values from the string. I can print the JSON but cannot seem to obtain individual elements.

I have tried json.loads() to ensure I am operating on a JSON object. To access the value associated with the "faceId" key, I tried the following but to no avail:

data = response.read()
dataStream = json.dumps(data)
faceIdentification = dataStream[0]['faceId']

I also attempted:

faceIdentification = dataStream['faceId']

and

faceIdentification = dataStream['faceId'][0]

I also tried directly operating on the JSON received but no luck. The JSON I want to obtain the faceId's value from is:

[{"faceId":"52f388ad-6789-4657-af4d-0dc308cc9aaa","faceRectangle":{"top":237,"left":204,"width":226,"height":226}}]
2
  • 4
    you means json.loads() not json.dumps() Commented Jan 11, 2017 at 14:52
  • Ah yes, that was the error. Commented Jan 12, 2017 at 11:44

2 Answers 2

2

JSON is a string format. To turn it into Python data structures, you "load" it:

data = response.read()
dataStream = json.loads(data)

Now dataStream is a list of dictionaries. The first of it is dataStream[0], and the 'faceId' element of it is dataStream[0]['faceId'].

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for that. The error was the "dump" section of the code
0

1) Accessing a json array obtained as a response for a GET request.

[{"symbol":"EURUSD","bid":1.13859,"ask":1.13911,"price":1.13885,"timestamp":1541215930}]

    json_data = json.loads(response.text)
    bid = json_data[0]['bid']
    ask = json_data[0]['ask']
    price = json_data[0]['price']
    timestamp = json_data[0]['timestamp']

2) Accessing a simple json without having an array as follows.

{"rates":{"EURUSD":{"rate":1.138789,"timestamp":1541224588014}},"code":200}

json_data = json.loads(response.text)
result = json_data['rates']['EURUSD']
rate = json_data['rates']['EURUSD']['rate']
timestamp = json_data['rates']['EURUSD']['timestamp']
code = json_data['code']

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.