Python jsonify что это

Working with JSON data | Learning Flask Ep. 9

Handle incoming, parsing and returning JSON data with Flask!

In this part of the “Learning Flask” series, we’re going to be working with JSON data.

JSON is an extremely popular format for sending and receiving data over the web. Flask provides us with some great tools to make light work of handling JSON data.

In this guide, we’re going to quickly cover how to handle incoming JSON data and return JSON data to the client.

Handling JSON

Let’s start out with a new route. This route will receive some JSON, parse the data, do some validation and return a new JSON response.

app/app/views.py

@app.route("/json") def json_example(): return "Thanks!" 

We’re going to be POSTing data to the server so we need to pass the methods argument to the @app.route() decorator, along with the HTTP methods we want to allow for this route:

app/app/views.py

@app.route("/json", methods=["POST"]) def json_example(): return "Thanks!" 

Working with any kind of request in Flask requires importing the request object. Go ahead and import it:

app/app/views.py

from flask import request 

Now we need a method to handle the incoming JSON. Flask provides the handy request.get_json() method, which parses any incoming JSON data into a Python dictionary.

Let’s store our incoming JSON data in a variable called req and print it out to the terminal:

app/app/views.py

@app.route("/json", methods=["POST"]) def json_example(): req = request.get_json() print(req) return "Thanks!" 

Whilst we’re here, let’s explicitly set an HTTP response by passing it to return :

app/app/views.py

@app.route("/json", methods=["POST"]) def json_example(): req = request.get_json() print(req) return "Thanks!", 200 

POSTing JSON

Let’s post some data to our route!

Tip — We’re going to use the free Postman app to make our requests, however, feel free to use an alternative such as curl or write a JavaScript function and call it from the browser (You’ll learn how to do this in the next episode!)

Go ahead and create a new POST request to the following URL:

Postman URL

We need to create some JSON data in the body of our request. Go ahead and click the raw tab and select JSON (application/json) from the dropdown list on the right.

Let’s just create a simple JSON object with 2 fields for now:

Postman body

cURL request

curl —header «Content-Type: application/json» —request POST —data » http://127.0.0.1:5000/json

Go ahead and click the Send button and look at the bottom of the app for the response body.

Postman response body

Now take a look in your terminal, you’ll see:

Awesome, We’ve posted some JSON data to Flask and received a response. You’ll also notice the response status at the bottom of the Postman app with 200 OK . Just as we told our route to do!

Читайте также:  Parsing string to number java

Parsing incoming JSON

We know using the get_json() method on the request object will return a Python dictionary with our JSON fields serielized into key/value pairs.

We can also validate and perform some conditional testing on our incoming request to determine if the body contains JSON data or not using the is_json check provided by Flask.

Let’s check that our response is JSON and return a response depending on what we receive:

app/app/views.py

@app.route("/json", methods=["POST"]) def json_example(): # Validate the request body contains JSON if request.is_json: # Parse the JSON into a Python dictionary req = request.get_json() # Print the dictionary print(req) # Return a string along with an HTTP status code return "JSON received!", 200 else: # The request body wasn't JSON so return a 400 HTTP status code return "Request was not JSON", 400 

We perform a conditional check using the if statement on the incoming request object to determine if the request body contains JSON or not.

If the request contains JSON, we’re printing it and returning the JSON received! string along with a 200 status code to indicate a successful transaction.

If the request body doesn’t contain JSON, we’re returning Request was not JSON along with a 400 HTTP status code to let the client know there was a bad request.

Go ahead and make another POST request in the Postman app to see the updates JSON received! response.

Postman response body

Now, change the dropdown menu in the Postman app from JSON (applicationjson) to text and click send to see the Request was not JSON message in the response, along with the 400 BAD REQUEST error.

Postman response body

Alright! So now you know how to handle incoming JSON. Let’s go ahead and return some!

Returning JSON

Again, Flask makes returning JSON a breeze using the the built in jsonify and make_response functions.

Let’s go ahead and import them:

app/app/views.py

from flask import jsonify, make_response

Let’s refactor our /json route to use jsonify and make_response . We’ll discuss them after:

app/app/views.py

@app.route("/json", methods=["POST"]) def json_example(): if request.is_json: req = request.get_json() response_body = < "message": "JSON received!", "sender": req.get("name") >res = make_response(jsonify(response_body), 200) return res else: return make_response(jsonify(), 400) 

We’ve created a new response_body object using a dictionary and passed it some values.

We then use the make_response() function to prepare a response, to which we’ve provided 2 arguments:

  • jsonify(*args, **kwargs) wraps Python’s own json.dumps() method and will serialize Python strings, lists or dicts as a JSON string.
  • 200 is the HTTP status code we want to return.

Tip — jsonify(1, 2, 3) and jsonify([1, 2, 3]) will both serialize to [1, 2, 3]

By passing both of these arguments to the make_response() function, we can create our response ahead of returning it by storing it as a variable. In our case, the res variable.

We’ve also done the same under the else conditional, just with it all on one line to save some space.

Go ahead and repeat the same process in the Postman app or cURL to see the newly formatted responses.

Posting JSON (application/json) will return:

Postman response body

Changing the dropdown to Text and posting will return:

Postman response body

Wrapping up

Flask makes working with JSON easy, providing many useful functions and methods such as is_json , get_json() and jsonify() , along with helpful functions such as make_response() . Creating API’s, webhooks and handling JSON is only a few lines of code away!

Last modified · 28 Feb 2019

Источник

flask.jsonify¶

This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype. For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that both jsonify(1,2,3) and jsonify([1,2,3]) serialize to [1,2,3] .

For clarity, the JSON serialization behavior has the following differences from dumps() :

  1. Single argument: Passed straight through to dumps() .
  2. Multiple arguments: Converted to an array before being passed to dumps() .
  3. Multiple keyword arguments: Converted to a dict before being passed to dumps() .
  4. Both args and kwargs: Behavior undefined and will throw an exception.
from flask import jsonify @app.route('/_get_current_user') def get_current_user(): return jsonify(username=g.user.username, email=g.user.email, id=g.user.id) 

This will send a JSON response like this to the browser:

 "username": "admin", "email": "admin@localhost", "id": 42 > 

Changed in version 0.11: Added support for serializing top-level arrays. This introduces a security risk in ancient browsers. See JSON Security for details.

This function’s response will be pretty printed if it was not requested with X-Requested-With: XMLHttpRequest to simplify debugging unless the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to false. Compressed (not pretty) formatting currently means no indents and no spaces after separators.

Источник

Формат данных JSON в Python

JSON (JavaScript Object Notation) это легковесный формат обмена данными. Людям его легко читать и вести в нем записи, а компьютеры запросто справляются с его синтаксическим анализом и генерацией.

JSON основан на языке программирования JavaScript. Но этот текстовый формат не зависит от языка и среди прочих может использоваться в Python и Perl. В основном его применяют для передачи данных между сервером и веб-приложением.

JSON построен на двух структурах:

  • Набор пар «имя-значение». Они могут быть реализованы как объект, запись, словарь, хеш-таблица, список «ключей-значений» или ассоциативный массив.
  • Упорядоченный список значений. Его реализуют в виде массива, вектора, списка или последовательности.

JSON в Python

В Python есть ряд пакетов, поддерживающих JSON, в частности metamagic.json, jyson, simplejson, Yajl-Py, ultrajson, и json. В этом руководстве мы будем использовать json, имеющий «родную» поддержку в Python. Для проверки данных JSON мы можем воспользоваться этим сайтом, предоставляющим JSON-линтер.

Ниже приведен пример записи JSON. Как видим, представление данных очень похоже на словари Python.

Конвертируем JSON в объекты Python

Вышеуказанную JSON-строку мы можем спарсить при помощи метода json.loads() из модуля json . В итоге получим словарь Python.

import json my_json_string = """< "article": [ < "id":"01", "language": "JSON", "edition": "first", "author": "Derrick Mwiti" >, < "id":"02", "language": "Python", "edition": "second", "author": "Derrick Mwiti" >], "blog":[ < "name": "Datacamp", "URL":"datacamp.com" >] > """ to_python = json.loads(my_json_string)

Конвертируем объекты Python в JSON

Используя json.dumps() , мы можем сконвертировать объекты Python в формат JSON.

blog = to_json= json.dumps(blog)

Теперь давайте сравним типы данных в Python и JSON.

Python JSON
dict Object
list Array
tuple Array
str String
int Number
float Number
True true
False false
None null

Ниже мы покажем, как сконвертировать некоторые объекты Python в типы данных JSON.

Кортеж Python — в массив JSON

tuple_example = 'Mango', 'Banana', 'Apple' print(json.dumps(tuple_example))

Список Python — в массив JSON

list_example = ["Mango", 1, 3, 6, "Oranges"] print(json.dumps(list_example))

Строка Python — в строку JSON

string_example = "This is a cool example." print(json.dumps(string_example))

Булевы значения Python — в булевы значения JSON

boolean_value = False print(json.dumps(boolean_value))

Запись в файл JSON

Модуль json позволяет также записывать данные JSON в файл. Такие файлы сохраняют с расширением .json .

Давайте посмотрим, как это сделать. Для этого воспользуемся функцией open() с параметром w , сигнализирующим о том, что мы хотим записать в файл.

my_json_string = """< "article": [ < "id":"01", "language": "JSON", "edition": "first", "author": "Derrick Mwiti" >, < "id":"02", "language": "Python", "edition": "second", "author": "Derrick Mwiti" >], "blog":[ < "name": "Datacamp", "URL":"datacamp.com" >] > """ with open('test_file.json', 'w') as file: json.dump(my_json_string, file)

Чтение файлов JSON

Теперь продемонстрируем, как прочитать только что созданный нами файл JSON. Для его загрузки вызовем json.load() .

with open('test_file.json', 'r') as j: json_data = json.load(j) print(json_data)

json.load vs json.loads

json.load используют для загрузки файла, а json.loads – для загрузки строки (loads расшифровывается как «load string»).

json.dump vs json.dumps

Аналогично, json.dump применяется, если нужно сохранить JSON в файл, а json.dumps (dump string) – если данные JSON нам нужны в виде строки для парсинга или вывода.

Работа с данными JSON в Data Science

Иногда при работе над проектами, связанными с data science, требуется загрузить данные в формате JSON. Библиотека для анализа данных Pandas предоставляет для этого функцию .read_json . Как только данные загружены, мы конвертируем их в объект dataframe при помощи атрибута pandas.DataFrame .

import pandas as pd data = pd.read_json("https://api.github.com/users") df = pd.DataFrame(data)

Ограничения имплементации

Процесс кодирования в JSON называется сериализацией, а декодирования – десериализацией. Некоторые реализации десериализаторов имеют ограничения на:

  • размер принимаемых текстов JSON
  • максимальный уровень вложенности объектов и массивов JSON
  • диапазон точности чисел JSON
  • содержание и максимальную длину строк JSON.

Впрочем, подобные ограничения связаны только с типами данных Python и работой самого интерпретатора Python.

Формат JSON в разработке API

Одно из важнейших применений JSON – для разработки API в веб-приложениях. Этот формат очень полезен, ведь позволяет коллегам-разработчикам строить систему на основе наших API, используя любой язык, поддерживающий JSON. А такой поддержкой обладают практически все современные языки. На простом примере покажем, как вернуть JSON при разработке приложения на Python с фреймворком Flask. Flask предоставляет для этого модуль jsonify .

from flask import jsonify @app.route('/_get_current_user') def get_current_user(): return jsonify(username=g.user.username, email=g.user.email, > Эта программа отправит в браузер что-то вроде следующего:

Заключение

В этом уроке мы сделали небольшое введение в особенности работы с JSON в Python. Рассмотрели использование различных методов из модуля json, таких как json.load и json.dumps . Кроме того, мы разобрали, как загрузить данные в формате JSON для работы в проектах data science и как возвращать JSON при разработке API. Узнать больше о модуле json можно на его официальной странице на сайте Python.

Источник

Оцените статью