How to Parse JSON in a Python One-Liner?

5/5 - (1 vote)

Problem: How to Parse a JSON object as a Python One-Liner?

Example: Say, you have pulled a JSON object from a server using the curl command:

curl -s | python -mjson.tool
    "continent_code": "EU",
    "country": "Netherlands",
    "country_code": "NL",
    "timezone": "Europe/Amsterdam"


How to parse the resulting JSON object and extract, say, the value "Netherlands" associated to the "country" key?

Solution: The following one-liner accomplishes this:

curl -s | python -c 'import sys, json; print(json.load(sys.stdin)["country"])'

The command consists of multiple parts. Let’s go over them in a step-by-step manner:

  • curl -s — extract the JSON file from the server The -s flag stands for “silent” and it simply surpresses unnecessary information printed to the standard output.
  • curl ... | ... — the pipe operator | redirects the output of one program and use it as input to another program. In our example, it takes the JSON object and writes it to the standard input of the Python program described next.
  • python -c '...' — Runs the Python program enclosed in the single quote environment.
  • import sys, json; — imports the modules sys and json. The trailing semicolon indicates that this expression is ready and the next expression (what you would call a line in a multi-line Python script) is following.
  • print(json.load(sys.stdin)["country"]) — loads the JSON object from the standard input to which the JSON object was piped in step 2. Then, the dictionary key "country" is used to access the resulting value "Netherlands". The result is printed to the standard output.

Thus, the result is the string "Netherlands" in our example JSON file.

An alternative to this method is the jq library. You can find a full tutorial on this excellent website.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!