0

This is not much an error I am having but I would like the reason behind the following:

For example in a tutorial page we have

json_string = """
{
    "researcher": {
        "name": "Ford Prefect",
        "species": "Betelgeusian",
        "relatives": [
            {
                "name": "Zaphod Beeblebrox",
                "species": "Betelgeusian"
            }
        ]
    }
}
"""
data = json.loads(json_string)

Which is ok, but my question is why all the bother to put the json as a string and then call json.loads when the same thing can be obtained by

otro={
    "researcher": {
        "name": "Ford Prefect",
        "species": "Betelgeusian",
        "relatives": [
            {
                "name": "Zaphod Beeblebrox",
                "species": "Betelgeusian"
            }
        ]
    }
}

print(type(otro))
print(otro)
print(otro==data) #True
2
  • Having it as a string is a "real world" example of how python might get the json data, plaintext string you then need to "load" as json in order to interpret it. Commented Nov 2, 2022 at 9:28
  • I see. I got it! It is a "replacement" from reading it as a string and then handling it as json! Commented Nov 2, 2022 at 9:31

1 Answer 1

1

Because your second example is not JSON at all, that's Python. They have superficial similarities, but you are only confusing yourself by mixing them.

For example, the values None, True, and False are valid in Python but not in JSON, where they would be represented by null, true, and false, respectively. Another difference is in how Unicode characters are represented. Obviously there are also many Python constructs which cannot be represented in JSON at all.

Which to use in practice depends on your use case. If you are exercising or testing code which needs to work on actual JSON input, obviously pass it JSON, not something else. The example you are citing is obviously trying to demonstrate how to use JSON functions from Python, and the embedding of the example data in a string is just to make the example self-contained, where in reality you would probably be receiving the data from a file or network API.

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

1 Comment

I am planning to save it as a JSON file. "pass it JSON" meaning the first example?

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.