0

I have a following context received from a query in Python script (an example):

{ "active": false, "owner": "user1", "content": [ { "recordType": "test", "record": [ { "id": "1", "date": "Nov 30, 2017 12:00:00 AM", "link": "http://localhost", "Size": 1234, }, { "id": "3", "date": "Nov 21, 2017 06:00:00 AM", "link": "http://localhost", "Size": 3241, } ] } ] }

making this to json array works without errors:

data = json.loads(*string_above*)

as a result this works ok:

print data["owner"]

user1

also this is ok:

print data["content"]

[ { "recordType": "test", "record": [ { "id": "1", "date": "Nov 30, 2017 12:00:00 AM", "link": "http://localhost", "Size": 1234, }, { "id": "3", "date": "Nov 21, 2017 06:00:00 AM", "link": "http://localhost", "Size": 3241, } ]}

Now my problem is how can I make this a multidimensional array?

E.g. command

print data["content"]["record"]

gives an error:

TypeError: list indices must be integers, not str

what I was hoping to get is:

{ "id": "1", "date": "Nov 30, 2017 12:00:00 AM", "link": "http://localhost", "Size": 1234, }, { "id": "3", "date": "Nov 21, 2017 06:00:00 AM", "link": "http://localhost", "Size": 3241, }

Found many different comments on this kind of problem with Google but is there no a simple solution - what am I missing?

2 Answers 2

1

Simple answer - data["content"] is a list with one element. You could use

print data["content"][0]["record"]

You could use online json fromatters (for example this) to explore your json data.

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

1 Comment

Thanks, this I can understand and agree with n8sty as well for being confused :)
1

I think you're confused. Let's fix that. The initial object you're returning is a dict not an array (list in Python speak).

d = { "active": False, "owner": "user1", "content": [ { "recordType": "test", "record": [ { ": id": "1", "date": "Nov 30, 2017 12:00:00 AM", "link": "http://localhost", "Size": 1234, }, { "id": "3", "date": "Nov 21, 2017 06:00:00 AM", "link": "http://localhost", "Size": 3241, } ] } ] }
isinstance(d, dict)
# True

The thing you grab from d is a list:

isinstance(data["content"], list)
# True

whose elements need to be referenced using int. So, to get the first element of data['content'] which is a dict, you would do

c0 = data['content'][0]
isinstance(c0, dict)
# True

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.