-3

im trying to print the first object of this json file but it only prints the first char of it.

This is my code:

response = requests.get("http://jsonplaceholder.typicode.com/users")
data = response.json()
new_data = json.dumps(data, indent = 2)
print(str(new_data[0]))

result i was hoping for:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }

actual result:

[
DirtyBit
  • 15,671
  • 4
  • 26
  • 53
doostaay
  • 27
  • 6
  • `json.dumps` encodes a Python object ***to*** JSON. You're printing out the first character of a (JSON) string. – deceze Apr 03 '19 at 07:36
  • 1
    also the dump is redundant, if you want response in string rather than python dict, use `response.text` instead of `response.json` and then parsing it back to string. – Josef Korbel Apr 03 '19 at 07:38
  • 1
    No need to convert it to a `str` – DirtyBit Apr 03 '19 at 07:39
  • The return value of `json.dumps` already is a string. Just `print(new_data)`. If you only want the first entry of data, you should try `new_data = json.dumps(data[0], indent=2)`. – Sven Krüger Apr 03 '19 at 07:43

3 Answers3

0

json.dump the first element of the response:

import json

response = requests.get("http://jsonplaceholder.typicode.com/users")
data = response.json()
first_elem = json.dumps(data[0], indent=2)
print(first_elem)
DirtyBit
  • 15,671
  • 4
  • 26
  • 53
  • thanks this worked. it also works if i just leave out "json.dumps(data), indent=2" and use "print(data[0])". question: is there a way to indent it without using "json.dumps"? – doostaay Apr 03 '19 at 07:52
  • 1
    @doostaay you could try `pprint` or `pretify`: https://stackoverflow.com/questions/91810/is-there-a-pretty-printer-for-python-data – DirtyBit Apr 03 '19 at 07:56
0

Apparently response.json() already is a dictionary.

So if you try first_element = data[0] you would get what you are looking for.

And then, if you want to make it pretty :

json.dumps(first_element, indent = 2)

If you wish a JSON object to behave like a dictionary , take a look at

json.loads

https://docs.python.org/2/library/json.html

Also : What's the best way to parse a JSON response from the requests library?

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
Born Tbe Wasted
  • 604
  • 2
  • 13
-1

json.dumps results in a string.

You are printing the first word of the string by doing [0]

For the output that you want, do:

print(new_data)

vaku
  • 685
  • 7
  • 15