Home  >  Q&A  >  body text

python - Why after using requests.get the URL, the response content in .text is in the form of a dictionary, but type it is str

I use anaconda's jupyter to run the code,
I use the requests module to read the web page,

see the output The content is within curly brackets , and it is judged to be a dictionary , so I use the dict function to read the value, but it fails.

type() Found that its attribute was found to be str

After I used json, I found that the attribute changed to dict.

When the program reads this type of content in dictionary formWhen strings are read,
how to make them become dictionary attributes ?

学习ing学习ing2686 days ago947

reply all(3)I'll reply

  • 習慣沉默

    習慣沉默2017-06-12 09:23:24

    Please use the <> edit button to add code when asking questions in the future, so that others can try the code.

    Try the following code:

    x = eval(r.text)
    y = r.json()
    print (type(x), type(y))
    print (x==y)

    The result should be that both dictionaries have the same content. In other words:

    x = eval(r.text)  
    y = r.json()      
    • x is to execute the string of r.text directly as expressions to generate a dictionary

    • y is the json object returned by the r.json() method, which generates a dictionary

    So your question is:
    "When the program reads this type of dictionary content as a string, how to make it a dictionary attribute again?"
    You can change the question more accurately to:
    "String is an expression in the form of a dictionary. How to turn a string into a dictionary? "
    Then the answer is the built-in function eval()

    Of course, the requests module already has the .json() method, you can use it

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-12 09:23:24

    d = r.json()

    In this way, you will get dictionary d

    reply
    0
  • 迷茫

    迷茫2017-06-12 09:23:24

    There are still quotation marks outside

    reply
    0
  • Cancelreply