Python 101: An Intro to Working with JSON

Python 101: An Intro to Working with JSON

https://ift.tt/2FHolZR

JavaScript Object Notation, more commonly known as JSON, is a lightweight data interchange format inspired by JavaScript object literal syntax. JSON is easy for humans to read and write. It is also easy for computers to parse and generate. JSON is used for storing and exchanging data in much the same way that XML is used.

Python has a built-in library called json that you can use for creating, editing and parsing JSON. You can read all about this library here:

It would probably be helpful to know what JSON looks like. Here is an example of JSON from https://json.org:

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

From Python’s point of view, this JSON is a nested Python dictionary. You will find that JSON is always translated into some kind of native Python data type. In this article, you will learn about the following:

  • Encoding a JSON String
  • Decoding a JSON String
  • Saving JSON to Disk
  • Loading JSON from Disk
  • Validating JSON with json.tool

JSON is a very popular format that is often used in web applications. You will find that knowing how to interact with JSON using Python is useful in your own work.

Let’s get started!

Encoding a JSON String

Python’s json module uses dumps() to serialize an object to a string. The “s” in dumps() stands for “string”. It’s easier to see how this works by using the json module in some code:

>>> import json
>>> j = {"menu": {
...   "id": "file",
...   "value": "File",
...   "popup": {
...     "menuitem": [
...       {"value": "New", "onclick": "CreateNewDoc()"},
...       {"value": "Open", "onclick": "OpenDoc()"},
...       {"value": "Close", "onclick": "CloseDoc()"}
...     ]
...   }
... }}
>>> json.dumps(j)
'{"menu": {"id": "file", "value": "File", "popup": {"menuitem": [{"value": "New", '
'"onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, '
'{"value": "Close", "onclick": "CloseDoc()"}]}}}'

Here you use json.dumps(), which transforms the Python dictionary into a JSON string. The example’s output was modified to wrap the string for print. Otherwise the string would all be on one line.

Now you’re ready to learn how to write an object to disk!

Saving JSON to Disk

Python’s json module uses the dump() function to serialize or encode an object as a JSON formatted stream to a file-like object. File-like objects in Python are things like file handlers or objects that you create using Python’s io module.

Go ahead and create a file named create_json_file.py and add the following code to it:

# create_json_file.py

import json

def create_json_file(path, obj):
    with open(path, 'w') as fh:
        json.dump(obj, fh)

if __name__ == '__main__':
    j = {"menu": {
        "id": "file",
        "value": "File",
        "popup": {
          "menuitem": [
            {"value": "New", "onclick": "CreateNewDoc()"},
            {"value": "Open", "onclick": "OpenDoc()"},
            {"value": "Close", "onclick": "CloseDoc()"}
          ]
        }
      }}
    create_json_file('test.json', j)

In this example, you use json.dump(), which is for writing to a file or file-like object. It will write to the file-handler, fh.

Now you can learn about decoding a JSON string!

Decoding a JSON String

Decoding or deserializing a JSON string is done via the loads() method. loads() is the companion function to dumps(). Here is an example of its use:

>>> import json
>>> j_str = """{"menu": {
...   "id": "file",
...   "value": "File",
...   "popup": {
...     "menuitem": [
...       {"value": "New", "onclick": "CreateNewDoc()"},
...       {"value": "Open", "onclick": "OpenDoc()"},
...       {"value": "Close", "onclick": "CloseDoc()"}
...     ]
...   }
... }}
... """
>>> j_obj = json.loads(j_str)
>>> type(j_obj)
<class 'dict'>

Here you recreate the JSON code from earlier as a Python multi-line string. Then you load the JSON string using json.loads(), which converts it to a Python object. In this case, it converts the JSON to a Python dictionary.

Now you are ready to learn how to load JSON from a file!

Loading JSON from Disk

Loading JSON from a file is done using json.load(). Here is an example:

# load_json_file.py

import json

def load_json_file(path):
    with open(path) as fh:
        j_obj = json.load(fh)
    print(type(j_obj))


if __name__ == '__main__':
    load_json_file('example.json')

In this code, you open the passed in file as you have seen before. Then you pass the file-handler, fh, to json.load(), which will transform the JSON into a Python object.

You can also use Python’s json module to validate JSON. You will find out how to do that next.

Validating JSON with json.tool

Python’s json module provides a tool you can run on the command line to check and see if the JSON has the correct syntax. Here are a couple of examples:

$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
$ echo '{"1.2":3.4}' | python -m json.tool
{
    "1.2": 3.4
}

The first call passes the string, '{1.2:3.4}' to json.tool, which tells you that there is something wrong with the JSON code. The second example shows you how to the fix the issue. When the fixed string is passed in to json.tool, it will “pretty-print” the JSON back out instead of emitting an error.

Wrapping Up

The JSON format is used very often when working with web APIs and web frameworks. The Python language provides a nice tool for you to use to convert JSON to Python objects and back again in the json library.

In this chapter, you learned about the following:

  • Encoding a JSON String
  • Decoding a JSON String
  • Saving JSON to Disk
  • Loading JSON from Disk
  • Validating JSON with json.tool

You now have another useful tool that you can use Python for. With a little practice, you will be working with JSON in no time!

The post Python 101: An Intro to Working with JSON appeared first on The Mouse Vs. The Python.

Python

via The Mouse Vs. The Python https://ift.tt/2m5EqsN

September 15, 2020 at 01:23AM

Example Dashboards Built with Python

Example Dashboards Built with Python

https://ift.tt/3lDjnwT


Live Chat

We’ll need to share your messages (and your email address if you’re logged in) with our live chat provider, Drift. Here’s their privacy policy.

If you don’t want to do this, you can email us instead at contact@anvil.works.

Python

via Anvil Blog https://ift.tt/2tpqq5l

September 15, 2020 at 12:50PM

wxPython by Example – Drag-and-Drop an Image (Video)

wxPython by Example – Drag-and-Drop an Image (Video)

https://ift.tt/3jfcalY

In this tutorial, you will learn how to drag an image into your #wxPython application and display it to your user.

If you enjoy this video, you may want to check out my book, Creating GUI Applications with wxPython, available on Leanpub and Amazon.

The post wxPython by Example – Drag-and-Drop an Image (Video) appeared first on The Mouse Vs. The Python.

Python

via The Mouse Vs. The Python https://ift.tt/2m5EqsN

September 29, 2020 at 09:36AM

The Best Humidifier

The Best Humidifier

https://ift.tt/30T1kel

The Best Humidifier

The best humidifiers can relieve dry skin and sinuses, but running one for months involves a lot more maintenance work than most people have in mind. Great humidifiers do the job without much inconvenience, and that’s why we recommend the Honeywell HCM-350 Germ Free Cool Mist Humidifier—it’s quiet, durable, and easier to fill and clean than any other humidifier we’ve tested.

technology

via Wirecutter: Reviews for the Real World https://ift.tt/36ATBn1

October 9, 2020 at 08:03PM

Vitess Online Schema Migration Automation – Percona Live ONLINE Talk Preview

Vitess Online Schema Migration Automation – Percona Live ONLINE Talk Preview

https://ift.tt/34KAYfN

Percona Live Online Agenda Slot: Wed 21 Oct • New York 2:30 p.m. • London 7:30 p.m. • New Delhi 12:00 a.m. (Thur 22 Oct)

Abstract

For many, running an online schema migration operation is still a manual job: from building the correct command, through identifying where the migration should run and which servers are to be affected, to auditing progress and completing the migration. Sharded environment poses an additional burden, as any logical migration must be applied multiple times, once for each shard.

What if you could just issue an ALTER TABLE … statement, and have all that complexity automated away? Vitess, an open source sharding framework for MySQL, is in a unique position to do just that. This session shows how Vitess’s proxy/agent/topology architecture, together with gh-ost, are used to hide schema change complexity, and carefully schedule and apply schema migrations.

Why is your talk exciting?

My work unifies multiple open source solutions (gh-ost, freno, and others) in a single, managed place. Vitess becomes an infrastructure solution, which can automate away the complexities of schema migrations: running, tracking, handling errors, cleaning up. It offers a completely automated cycle for most users, yet still gives them the controls.

Whether with gh-ost or pt-online-schema-change, vitess is able to abstract away the migration process such that the user will normally just run and forget. Having worked as an operational engineer, and having developed schema migration automation in my past experience, I’m just excited to think about the users who will save hours of manual labor a week with this new offering.

Who would benefit the most from your talk?

Operational DBAs and engineers who perform manual schema migrations, or are looking to automate their database infrastructure.

What other talks are you most looking forward to?

I’m in particular curious to hear about what’s new in distributed databases and geo replication. Otherwise, as always, I’m keen to hear about open source tools in the MySQL ecosystem.

Is there any other question you would like to answer?

Q: Is this work public?

A: Yes, it is. This work is expected to be released as an experimental feature as part of Vitess 8.0, end of October 2020. It is public, free and open source.

The post Vitess Online Schema Migration Automation – Percona Live ONLINE Talk Preview appeared first on Percona Community Blog.

technology

via Planet MySQL https://ift.tt/2iO8Ob8

October 9, 2020 at 08:53PM

Knife Aid Knife Sharpening Service

Knife Aid Knife Sharpening Service

https://ift.tt/34DlmdS

Knife Aid Knife Sharpening Service

 | Buy

You can sharpen knives yourself, but you’ll never get them as sharp as a professional can. Knife Aid’s mail-in kit lets you ship up to five knives to their team of expert knife smiths, then ships them back to you within about a week, often sharper than the day you bought them.

fun

via The Awesomer https://theawesomer.com

October 9, 2020 at 11:44AM

How Candy Corn Is Made

How Candy Corn Is Made

https://ift.tt/2GGdjoJ

How Candy Corn Is Made

Link

We’ve seen two different ways how NOT to make candy corn, now watch how the pros do it. This 2014 clip from The Washington Post takes us inside of the Jelly Belly factory in Illinois for an explanation of the “kernel” making process starting from individual ingredients until they’re bagged and show up on store shelves.

fun

via The Awesomer https://theawesomer.com

October 9, 2020 at 12:30PM

Defending Against Riots and Mobs – Armed Citizens Legal Defense Network

Defending Against Riots and Mobs – Armed Citizens Legal Defense Network

https://ift.tt/30OjPR8

And as usual, I need to readjust a couple of my strategies to follow the good advice given my Marty Hays and Massad Ayoob.  This is not a Chest Thumping video, this is a survive (in more ways than one) video.  Make time since it is long and pay attention.

guns

via https://gunfreezone.net

October 9, 2020 at 06:09AM

Laravel Surveillance

Laravel Surveillance

https://ift.tt/36MAEQc


Laravel Surveillance is a package by Neelkanth Kaushik to put malicious users, IP addresses, and anonymous browser fingerprints under surveillance. Once a user is under supervision, this package logs the URLs they visit and even blocks users deemed malicious.

This package consists of a CLI to manage surveillance and a PHP API to survey users programmatically.

Here’s a few CLI examples of what this package can do:

# Survey ip, user id, browser fingerprints
php artisan surveillance:enable ip 192.1.2.4
php artisan surveillance:enable userid 1234
php artisan surveillance:enable fingerprint hjP0tLyIUy7SXaSY6gyb

# Block IP, user id, etc.
php artisan surveillance:block ip 192.1.2.4
php artisan surveillance:block userid 1234
php artisan surveillance:block fingerprint hjP0tLyIUy7SXaSY6gyb

Using the package’s PHP API, you can do the same things programmatically:

use Neelkanth\Laravel\Surveillance\Services\Surveillance;

// Enable IP surveillance
Surveillance::manager()
    ->type("ip")
    ->value("192.5.4.1")
    ->enableSurveillance();

// Block User
Surveillance::manager()
    ->type("userid")
    ->value(2121)
    ->blockAccess();

You can learn more about this package, get full installation instructions, and view the source code on GitHub at neelkanthk/laravel-surveillance.

Filed in:
News

programming

via Laravel News https://ift.tt/14pzU0d

October 9, 2020 at 09:22AM

You Can Rack up as Much as $165 in Amazon Credit To Spend on Prime Day, Here’s How

You Can Rack up as Much as $165 in Amazon Credit To Spend on Prime Day, Here’s How

https://ift.tt/2GP7TYo


Top Offer: Spend $10 at Amazon Small Biz, Get $10 Back

Amazon Prime Day is less than a week away, delivering a 2-day bonanza of fantastic deals all across the retailer. We’re expecting thousands of items on sale, including some of the best prices we’ve seen all year.

If you’re planning on jumping on some serious deals come October 13-14, Amazon is offering a handful of ways to build up a cache of Prime Day credit that Prime members can spend freely during the event. You can earn Prime Day credit by buying groceries at Whole Foods, for example, or shopping at Amazon-partnered small businesses.

All told, as of this writing, you can earn up to $165 dollars in Amazon credit. Here are the promotions that Amazon is offering ahead of Prime Day.

Here’s one promo that yields considerable returns for a good cause: Support small business, and still get a bonus reward in the end. Simply spend $10 or more at one of the small businesses of Amazon’s choice and you’ll get a $10 Prime Day credit (limit one per customer). Whether it’s pet supplies, toys, skincare, or electronics, you’re bound to find something you’d like.

G/O Media may get a commission

Need groceries? Perfect: Prime members who shop at Whole Foods and spend at least $10 in a single transaction will get a $10 Amazon credit specifically for Prime Day. Whether you shop in-store, online, or via the mobile app, you’ll get the bonus bucks (one per customer).

If you have an Amazon Books or Amazon Pop-Up physical retailer near you and don’t mind making a visit in the next week, you’ll get a $10 Prime Day credit after spending at least $10 at either store. Amazon has 29 total locations in the United States between the two store types, although you’ll only get credit at one or the other (not both).

Amazon 4-Star is another type of Amazon retail store, featuring an array of items with at least a 4-star rating on the site—including books, gadgets, kitchen appliances, and more. Still, you can take home a separate $10 Prime Day credit if you spend at least $10 at a 4-Star store, separate from the aforementioned Books/Pop-Up deal. Amazon currently has 4-Star stores open in 15 states, with more on the horizon.

What’s this? Another Amazon retail shop? Amazon Go is a bit different, taking a contactless approach in which you can get things like breakfast, lunch, and snacks without dealing with a cashier—the items you carry out are billed to the Amazon account on your phone. As with the other shops, you’ll get a $10 Prime Day credit for spending at least $10 at an Amazon Go location.

Here’s a promotion in the same Prime Day window that doesn’t lock you to spending earned credit during Prime Day itself. Right now, if you spend $20 or more on eBooks via Amazon’s Kindle platform by October 12, you’ll get a $5 credit towards future eBooks. The credit is good for 21 days upon receipt, so at least you’ll have wiggle room to pick your next reads after Prime Day.

If you happen to live in the vicinity of the single current Amazon Fresh grocery store in Woodland Hills, California, then you can take advantage of this bargain. Spend $10 or more at the store between now and October 14 and scan the QR code in your Amazon app and you’ll get a $10 credit for Prime Day. According to the terms and conditions, this deal does not apply to the Amazon Fresh delivery service, only in-store purchases. More Amazon Fresh stores are coming to California and the Chicago area, but at least for now, this promo is exclusive to that one location.

If you shop at Amazon a lot and are on the hunt for a new credit card—or possibly a better one than what you have—then this deal might entice you to apply for the Amazon Prime Rewards Credit Card. Sign up now, and you’ll get a $100 Amazon gift card you can spend whenever you want. A lesser deal is available to non-Prime members, as well: Sign up for the standard Amazon Rewards Credit Card and you’ll receive a $50 Amazon gift card. The standard card has fewer benefits, but you will need a Prime subscription to sign up for the Prime Rewards card mentioned above.


geeky,Tech

via Gizmodo https://gizmodo.com

October 8, 2020 at 06:39PM