0

JSON data:

[
 {
  "id": 2,
  "name": "An ice sculpture",
  "price": 12.50,
 },

 {
  "id": 3,
  "name": "A blue mouse",
  "price": 25.50,
 }
]

Expected output:

id - 2
name - An ice sculpture
price - 12.50

Something similar for id = 3.

Update

What I did so far:

content = urllib.request.urlopen(url).read().decode('utf-8')
content = content.replace("//" , "").strip() #there is a // at the beginning
obj = json.loads(content)
for obj in content:
    for key, value in obj.items():
        print (obj.key, obj.value)

Error:

File "test.py", line 22, in get
for key, value in obj.items():
AttributeError: 'str' object has no attribute 'items'

I've seen mostly data is accessed directly using the attribute keys like obj[0]["id"] outputs 2. Is there any way I can get the expected output without accessing the keys explicitly?

4
  • What is obj? It looks like a list, but you seem to think it's a dictionary Commented Nov 26, 2016 at 17:48
  • What do you mean of without accessing the keys explicitly? Commented Nov 26, 2016 at 17:52
  • @mohammad In obj[0]["id"] I have to mention the key "id' to retrieve its value. I want it to be in a generalized form. Commented Nov 26, 2016 at 18:04
  • @cricket_007 I've edited my question. Commented Nov 26, 2016 at 18:11

2 Answers 2

3

You have a list of dictionaries. Your code would work, as long as you iterate through the outer list:

for obj in my_json_data:
    for key, value in obj.items():
         print (obj.key, obj.value)
Sign up to request clarification or add additional context in comments.

8 Comments

Why are you asking me? You were the one that posted it in the question.
No, I'm getting an error that str object has no attribute items. I think there is a data type error. And, I've edited my question with additional code.
@AlphaQ - you showed the JSON in your question. If you'd like more help, you need to add the URL so we can reproduce the actual problems you're having
There's no way that this code doesn't work while my_json_data[0]['id'] does.
But that shows that your object is a string. So content[0]["id"] cannot possibly have worked.
|
0

you should try this

data = [
 {
  "id": 2,
  "name": "An ice sculpture",
  "price": 12.50,
 },

 {
  "id": 3,
  "name": "A blue mouse",
  "price": 25.50,
 }
]

for json_data in data:
    for k, v in json_data.items():
        print('{} - {}'.format(k,v))

1 Comment

how about the print statement where I actually got the format OP requested?

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.