How to Parse JSON in a Python One-Liner?

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 http://example.com | python -mjson.tool
{
    "continent_code": "EU",
    "country": "Netherlands",
    "country_code": "NL",
    ...
    "timezone": "Europe/Amsterdam"
}

Source

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 http://example.com | 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 http://example.com — extract the JSON file from the server http://example.com. 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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!