Python json encoding using json.dump and dumps(): write json into file and string

How to use parse_float and parse_int kwarg in json.load()

As I already told  and , both are optional parameters but, if specified, will be called with the string of every JSON float and integer to be decoded. By default, this is equivalent to and .

Suppose the JSON document contains many float values, and you want to round all float values to two decimal-point. In this case, we need to define a custom function that performs whatever rounding you desire. We can pass such a function to   kwarg.

Also, if you wanted to perform any operation on integer values, we could write a custom function and pass it to  kwarg. For example, you received leave days in the JSON document, and you want to calculate the salary to deduct.

We are using the following JSON file for this example.

Insert image.

Output:

Load float and int values from JSON and manipulate it
Started Reading JSON file
Salary:  9250.542
<class 'float'>
Salary to deduct:  3
Done reading a JSON file

Performance

Serialization and deserialization performance of orjson is better than
ultrajson, rapidjson, simplejson, or json. The benchmarks are done on
fixtures of real data:

  • twitter.json, 631.5KiB, results of a search on Twitter for «一», containing
    CJK strings, dictionaries of strings and arrays of dictionaries, indented.

  • github.json, 55.8KiB, a GitHub activity feed, containing dictionaries of
    strings and arrays of dictionaries, not indented.

  • citm_catalog.json, 1.7MiB, concert data, containing nested dictionaries of
    strings and arrays of integers, indented.

  • canada.json, 2.2MiB, coordinates of the Canadian border in GeoJSON
    format, containing floats and arrays, indented.

Latency

twitter.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.59 1698.8 1
ujson 2.14 464.3 3.64
rapidjson 2.39 418.5 4.06
simplejson 3.15 316.9 5.36
json 3.56 281.2 6.06

twitter.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 2.28 439.3 1
ujson 2.89 345.9 1.27
rapidjson 3.85 259.6 1.69
simplejson 3.66 272.1 1.61
json 4.05 246.7 1.78

github.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.07 15265.2 1
ujson 0.22 4556.7 3.35
rapidjson 0.26 3808.9 4.02
simplejson 0.37 2690.4 5.68
json 0.35 2847.8 5.36

github.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.18 5610.1 1
ujson 0.28 3540.7 1.58
rapidjson 0.33 3031.5 1.85
simplejson 0.29 3385.6 1.65
json 0.29 3402.1 1.65

citm_catalog.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.99 1008.5 1
ujson 3.69 270.7 3.72
rapidjson 3.55 281.4 3.58
simplejson 11.76 85.1 11.85
json 6.89 145.1 6.95

citm_catalog.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 4.53 220.5 1
ujson 5.67 176.5 1.25
rapidjson 7.51 133.3 1.66
simplejson 7.54 132.7 1.66
json 7.8 128.2 1.72

canada.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 4.72 198.9 1
ujson 17.76 56.3 3.77
rapidjson 61.83 16.2 13.11
simplejson 80.6 12.4 17.09
json 52.38 18.8 11.11

canada.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 10.28 97.4 1
ujson 16.49 60.5 1.6
rapidjson 37.92 26.4 3.69
simplejson 37.7 26.5 3.67
json 37.87 27.6 3.68

Memory

orjson’s memory usage when deserializing is similar to or lower than
the standard library and other third-party libraries.

This measures, in the first column, RSS after importing a library and reading
the fixture, and in the second column, increases in RSS after repeatedly
calling on the fixture.

Library import, read() RSS (MiB) loads() increase in RSS (MiB)
orjson 13.5 2.5
ujson 14 4.1
rapidjson 14.7 6.5
simplejson 13.2 2.5
json 12.9 2.3

github.json

Library import, read() RSS (MiB) loads() increase in RSS (MiB)
orjson 13.1 0.3
ujson 13.5 0.3
rapidjson 14 0.7
simplejson 12.6 0.3
json 12.3 0.1

citm_catalog.json

Library import, read() RSS (MiB) loads() increase in RSS (MiB)
orjson 14.6 7.9
ujson 15.1 11.1
rapidjson 15.8 36
simplejson 14.3 27.4
json 14 27.2

canada.json

Library import, read() RSS (MiB) loads() increase in RSS (MiB)
orjson 17.1 15.7
ujson 17.6 17.4
rapidjson 18.3 17.9
simplejson 16.9 19.6
json 16.5 19.4

Reproducing

The above was measured using Python 3.8.3 on Linux (x86_64) with
orjson 3.3.0, ujson 3.0.0, python-rapidson 0.9.1, and simplejson 3.17.2.

The latency results can be reproduced using the and
scripts. The memory results can be reproduced using the script.

Пример десериализации JSON Python

На этот раз, представьте что у вас есть некие данные, хранящиеся на диске, которыми вы хотите манипулировать в памяти. Вам все еще нужно будет воспользоваться контекстным менеджером, но на этот раз, вам нужно будет открыть существующий data_file.json в режиме для чтения.

Python

with open(«data_file.json», «r») as read_file:
data = json.load(read_file)

1
2

withopen(«data_file.json»,»r»)asread_file

data=json.load(read_file)

Здесь все достаточно прямолинейно, но помните, что результат этого метода может вернуть любые доступные типы данных из таблицы конверсий

Это важно только в том случае, если вы загружаете данные, которые вы ранее не видели. В большинстве случаев, корневым объектом будет dict или list

Если вы внесли данные JSON из другой программы, или полученную каким-либо другим способом строку JSON форматированных данных в Python, вы можете легко десериализировать это при помощи loads(), который естественно загружается из строки:

Python

json_string = «»»
{
«researcher»: {
«name»: «Ford Prefect»,
«species»: «Betelgeusian»,
«relatives»:
}
}
«»»

data = json.loads(json_string)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

json_string=»»»

{
    «researcher»: {
        «name»: «Ford Prefect»,
        «species»: «Betelgeusian»,
        «relatives»: [
            {
                «name»: «Zaphod Beeblebrox»,
                «species»: «Betelgeusian»
            }

    }
}
«»»
 

data=json.loads(json_string)

Ву а ля! Вам удалось укротить дикого JSON, теперь он под вашим контролем. Но что вы будете делать с этой силой — остается за вами. Вы можете кормить его, выращивать, и даже научить новым приемам. Не то чтобы я не доверяю вам, но держите его на привязи, хорошо?

A Real World Example (sort of)

For your introductory example, you’ll use JSONPlaceholder, a great source of fake JSON data for practice purposes.

First create a script file called , or whatever you want. I can’t really stop you.

You’ll need to make an API request to the JSONPlaceholder service, so just use the package to do the heavy lifting. Add these imports at the top of your file:

Now, you’re going to be working with a list of TODOs cuz like…you know, it’s a rite of passage or whatever.

Go ahead and make a request to the JSONPlaceholder API for the endpoint. If you’re unfamiliar with , there’s actually a handy method that will do all of the work for you, but you can practice using the library to deserialize the attribute of the response object. It should look something like this:

You don’t believe this works? Fine, run the file in interactive mode and test it for yourself. While you’re at it, check the type of . If you’re feeling adventurous, take a peek at the first 10 or so items in the list.

>>>

See, I wouldn’t lie to you, but I’m glad you’re a skeptic.

All right, time for some action. You can see the structure of the data by visiting the endpoint in a browser, but here’s a sample TODO:

There are multiple users, each with a unique , and each task has a Boolean property. Can you determine which users have completed the most tasks?

Yeah, yeah, your implementation is better, but the point is, you can now manipulate the JSON data as a normal Python object!

I don’t know about you, but when I run the script interactively again, I get the following results:

>>>

That’s cool and all, but you’re here to learn about JSON. For your final task, you’ll create a JSON file that contains the completed TODOs for each of the users who completed the maximum number of TODOs.

All you need to do is filter and write the resulting list to a file. For the sake of originality, you can call the output file . There are may ways you could go about this, but here’s one:

Perfect, you’ve gotten rid of all the data you don’t need and saved the good stuff to a brand new file! Run the script again and check out to verify everything worked. It’ll be in the same directory as when you run it.

Now that you’ve made it this far, I bet you’re feeling like some pretty hot stuff, right? Don’t get cocky: humility is a virtue. I am inclined to agree with you though. So far, it’s been smooth sailing, but you might want to batten down the hatches for this last leg of the journey.

Exceptions Related to JSON Library in Python:

  • Class json.JSONDecoderError handles the exception related to decoding operation. and it’s a subclass of ValueError.
  • Exception — json.JSONDecoderError(msg, doc)
  • Parameters of Exception are,
    • msg – Unformatted Error message
    • doc – JSON docs parsed
    • pos – start index of doc when it’s failed
    • lineno – line no shows correspond to pos
    • colon – column no correspond to pos

Example,

import json
#File I/O Open function for read data from JSON File
data = {} #Define Empty Dictionary Object
try:
        with open('json_file_name.json') as file_object:
                data = json.load(file_object)
except ValueError:
     print("Bad JSON file format,  Change JSON File")

Python поддерживает JSON

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

Просто импортируйте модуль в начале вашего файла:

Python

import json

1 importjson

Небольшой словарь

Как правило, процесс кодирования JSON называется сериализация. Этот термин обозначает трансформацию данных в серию байтов (следовательно, серийных) для хранения или передачи по сети. Также вы, возможно, уже слышали о термине «маршалинг», но это уже совсем другая область.

Естественно, десериализация — является противоположным процессом декодирования данных, которые хранятся или направлены в стандарт JSON.

명령 줄 인터페이스¶

소스 코드: Lib/json/tool.py

모듈은 JSON 객체의 유효성을 검사하고 예쁘게 인쇄하는 간단한 명령 줄 인터페이스를 제공합니다.

선택적 과 인자가 지정되지 않으면, 각각 과 이 사용됩니다:

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

버전 3.5에서 변경: 출력은 이제 입력과 같은 순서입니다. 딕셔너리의 출력을 키에 대해 알파벳 순으로 정렬하려면 옵션을 사용하십시오.

명령 줄 옵션

유효성을 검사하거나 예쁘게 인쇄할 JSON 파일:

$ python -m json.tool mp_films.json

    {
        "title": "And Now for Something Completely Different",
        "year": 1971
    },
    {
        "title": "Monty Python and the Holy Grail",
        "year": 1975
    }

infile이 지정되지 않으면, 에서 읽습니다.

infile의 출력을 지정된 outfile에 씁니다. 그렇지 않으면, 에 씁니다.

딕셔너리의 출력을 키에 대해 알파벳 순으로 정렬합니다.

버전 3.5에 추가.

비 ASCII 문자의 이스케이프를 비활성화합니다. 자세한 내용은 를 참조하십시오.

버전 3.9에 추가.

모든 입력 행을 별도의 JSON 객체로 구문 분석합니다.

버전 3.8에 추가.

공백 제어를 위한 상호 배타적 옵션.

버전 3.9에 추가.

도움말 메시지를 표시합니다.

각주

the errata for RFC 7159에서 언급했듯이, JSON은 문자열에 U+2028(LINE SEPARATOR)과 U+2029(PARAGRAPH SEPARATOR) 문자를 허용하지만, JavaScript(ECMAScript Edition 5.1 기준)는 허용하지 않습니다.

Number¶

The JSON specification only contains one numeric type, “number”. The C
programming language has distinct types for integer and floating-point
numbers, so for practical reasons Jansson also has distinct types for
the two. They are called “integer” and “real”, respectively. For more
information, see .

json_int_t

This is the C type that is used to store JSON integer values. It
represents the widest integer type available on your system. In
practice it’s just a typedef of long long if your compiler
supports it, otherwise long.

Usually, you can safely use plain int in place of
json_int_t, and the implicit C integer conversion handles the
rest. Only when you know that you need the full 64-bit range, you
should use json_int_t explicitly.

JSON_INTEGER_IS_LONG_LONG

JSON_INTEGER_FORMAT

*json_integer( value)
Return value: New reference.

Returns a new JSON integer, or NULL on error.

json_integer_value(const  *integer)

Returns the associated value of integer, or 0 if json is not a
JSON integer.

int json_integer_set(const  *integer,  value)

Sets the associated value of integer to value. Returns 0 on
success and -1 if integer is not a JSON integer.

*json_real(double value)
Return value: New reference.

Returns a new JSON real, or NULL on error.

double json_real_value(const  *real)

Returns the associated value of real, or 0.0 if real is not a
JSON real.

int json_real_set(const  *real, double value)

Sets the associated value of real to value. Returns 0 on
success and -1 if real is not a JSON real.

In addition to the functions above, there’s a common query function
for integers and reals:

Десериализация JSON

Отлично, похоже вам удалось поймать экземпляр дикого JSON! Теперь нам нужно предать ему форму. В модуле json вы найдете load() и loads() для превращения кодированных данных JSON в объекты Python.

Как и сериализация, есть простая таблица конверсии для десериализации, так что вы можете иметь представление о том, как все выглядит.

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Технически, эта конверсия не является идеальной инверсией таблицы сериализации. По сути, это значит что если вы кодируете объект сейчас, а затем декодируете его в будущем, вы можете не получить тот же объект назад. Я представляю это как своего рода телепортацию: мои молекулы распадаются в точке А и собираются в точке Б. Буду ли я тем же самым человеком?

В реальности, это как попросить одного друга перевести что-нибудь на японский, а потом попросить другого друга перевести это обратно на русский. В любом случае, самым простым примером будет кодировать кортеж и получить назад список после декодирования, вот так:

Python

blackjack_hand = (8, «Q»)
encoded_hand = json.dumps(blackjack_hand)
decoded_hand = json.loads(encoded_hand)

print(blackjack_hand == decoded_hand) # False

print(type(blackjack_hand)) # <class ‘tuple’>
print(type(decoded_hand)) # <class ‘list’>

print(blackjack_hand == tuple(decoded_hand)) # True

1
2
3
4
5
6
7
8
9
10

blackjack_hand=(8,»Q»)

encoded_hand=json.dumps(blackjack_hand)

decoded_hand=json.loads(encoded_hand)

print(blackjack_hand==decoded_hand)# False

print(type(blackjack_hand))# <class ‘tuple’>

print(type(decoded_hand))# <class ‘list’>

print(blackjack_hand==tuple(decoded_hand))# True

Parsing and Validating Values¶

This sectinon describes functions that help to validate complex values
and extract, or unpack, data from them. Like , this is also based on format strings.

While a JSON value is unpacked, the type specified in the format
string is checked to match that of the JSON value. This is the
validation part of the process. In addition to this, the unpacking
functions can also check that all items of arrays and objects are
unpacked. This check be enabled with the format character ! or by
using the flag JSON_STRICT. See below for details.

Here’s the full list of format characters. The type in parentheses
denotes the JSON type, and the type in brackets (if any) denotes the C
type whose address should be passed.

s (string)
Convert a JSON string to a pointer to a NULL terminated UTF-8
string. The resulting string is extracted by using
internally, so it exists as long as
there are still references to the corresponding JSON string.
n (null)
Expect a JSON null value. Nothing is extracted.
b (boolean)
Convert a JSON boolean value to a C int, so that true
is converted to 1 and false to 0.
i (integer)
Convert a JSON integer to C int.
I (integer)
Convert a JSON integer to C .
f (real)
Convert a JSON real to C double.
F (integer or real)
Convert a JSON number (integer or real) to C double.
o (any value)
Store a JSON value with no conversion to a pointer.
O (any value)
Like O, but the JSON value’s reference count is incremented.
(array)
Convert each item in the JSON array according to the inner format
string. fmt may contain objects and arrays, i.e. recursive
value extraction is supporetd.
{fmt} (object)

Convert each item in the JSON object according to the inner format
string fmt. The first, third, etc. format character represent
a key, and must be s. The corresponding argument to unpack
functions is read as the object key. The second fourth, etc.
format character represent a value and is written to the address
given as the corresponding argument. Note that every other
argument is read from and every other is written to.

fmt may contain objects and arrays as values, i.e. recursive
value extraction is supporetd.

!
This special format character is used to enable the check that
all object and array items are accessed, on a per-value basis. It
must appear inside an array or object as the last format character
before the closing bracket or brace. To enable the check globally,
use the JSON_STRICT unpacking flag.
*
This special format character is the opposite of !. If the
JSON_STRICT flag is used, * can be used to disable the
strict check on a per-value basis. It must appear inside an array
or object as the last format character before the closing bracket
or brace.

The following functions compose the parsing and validation API:

int json_unpack( *root, const char *fmt, …)

Validate and unpack the JSON value root according to the format
string fmt. Returns 0 on success and -1 on failure.

int json_unpack_ex( *root,  *error, size_t flags, const char *fmt, …)
int json_vunpack_ex( *root,  *error, size_t flags, const char *fmt, va_list ap)

Validate and unpack the JSON value root according to the format
string fmt. If an error occurs and error is not NULL, write
error information to error. flags can be used to control the
behaviour of the unpacker, see below for the flags. Returns 0 on
success and -1 on failure.

Note

The first argument of all unpack functions is json_t *root
instead of const json_t *root, because the use of O format
character causes the reference count of root, or some value
reachable from root, to be increased. Furthermore, the o
format character may be used to extract a value as-is, which allows
modifying the structure or contents of a value reachable from
root.

If the O and o format character are not used, it’s
perfectly safe to cast a const json_t * variable to plain
json_t * when used with these functions.

The following unpacking flags are available:

JSON_STRICT
Enable the extra validation step checking that all object and
array items are unpacked. This is equivalent to appending the
format character ! to the end of every array and object in the
format string.
JSON_VALIDATE_ONLY
Don’t extract any data, just validate the JSON value against the
given format string. Note that object keys must still be specified
after the format string.

Examples:

Загрузка данных из фала pickle.

Теперь переключитесь во вторую консоль Python — т. е. не в ту где вы создали словарь entry.

>>> shell                                    ①2>>> entry                                    ②
Traceback (most recent call last):
  File «<stdin>», line 1, in <module>NameError: name ‘entry’ is not defined>>> import pickle>>> with open(‘entry.pickle’, ‘rb’) as f:    ③
…     entry = pickle.load(f)               ④
…>>> entry                                    ⑤{‘comments_link’: None,
 ‘internal_id’: b’\xDE\xD5\xB4\xF8′,
 ‘title’: ‘Dive into history, 2009 edition’,
 ‘tags’: (‘diveintopython’, ‘docbook’, ‘html’),
 ‘article_link’:
 ‘http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition’,
 ‘published_date’: time.struct_time(tm_year=2009, tm_mon=3, tm_mday=27, tm_hour=22, tm_min=20, tm_sec=42, tm_wday=4, tm_yday=86, tm_isdst=-1),
 ‘published’: True}

① Это вторая консоль Python

② Здесь не определена переменная entry. Вы определяли переменную entry в первой консоли Python, но это полностью отличное окружение со своим собственным состоянием.

③ Откроем entry.pickle файл, который вы создали в первой консоли Python. Модуль pickle использует двоичный формат представления данных, поэтому вам всегда нужно открывать файл в двоичном режиме.

④ Функция pickle.load() принимает на вход поток, читает сериализованные данные из потока, создает новый объект Python, восстанавливает сериализованные данные в новый объект Python, и возвращает новый объект Python.

⑤ Теперь переменная entry — это словарь со знакомыми ключами и значениями.

Результат цикла pickle.dump()/pickle.load() это новая структура данных эквивалентная оригинальной структуре данных.

>>> shell                                    ①1>>> with open(‘entry.pickle’, ‘rb’) as f:    ②
…     entry2 = pickle.load(f)              ③
…>>> entry2 == entry                          ④True>>> entry2 is entry                          ⑤False>>> entry2’tags’                           ⑥(‘diveintopython’, ‘docbook’, ‘html’)>>> entry2’internal_id’
b’\xDE\xD5\xB4\xF8′

① Переключитесь обратно в первую консоль Python.

② Откройте entry.pickle файл

③ Загрузите сериализованные данные в новую переменную entry2

④ Python подтверждает, что эти два словаря(entry и entry2) эквивалентны. В этой консоли вы создали entry с нуля, начиная с пустого словаря вручную присваивая значения ключам. Вы сериализовали этот словарь и сохранили в файле entry.pickle. Теперь вы считали сериализованные данные из этого фала и создали совершенную копию оригинальной структуры.

⑤ Эквивалентность не значит идентичности. Я сказал, что вы создали _идеальную копию_ оригинальной структуры данных, и это правда. Но это все же копия.

⑥ По причинам которые станут ясны в дальнейшем, я хочу указать, что значения ключа ‘tags’ это кортеж, и значение ‘internal_id’ это объект bytes.

Много статей о модуле Pickle ссылаются на cPickle. В Python 2 существует две реализации модуля pickle одна написана на чистом Python а другая на C(но все же вызываема из Python). В Python 3 эти два модуля были объеденены поэтому вам следует всегда использовать import pickle. Вам могут быть плезны эти статьи но следует игнорировать устаревшую информацию о cPickle.

19.2.2. Encoders and Decoders¶

class (object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)

Simple JSON decoder.

Performs the following translations in decoding by default:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

It also understands , , and as their
corresponding values, which is outside the JSON spec.

object_hook, if specified, will be called with the result of every JSON
object decoded and its return value will be used in place of the given
. This can be used to provide custom deserializations (e.g. to
support JSON-RPC class hinting).

object_pairs_hook, if specified will be called with the result of every
JSON object decoded with an ordered list of pairs. The return value of
object_pairs_hook will be used instead of the . This
feature can be used to implement custom decoders that rely on the order
that the key and value pairs are decoded (for example,
will remember the order of insertion). If
object_hook is also defined, the object_pairs_hook takes priority.

Changed in version 3.1: Added support for object_pairs_hook.

parse_float, if specified, will be called with the string of every JSON
float to be decoded. By default, this is equivalent to .
This can be used to use another datatype or parser for JSON floats
(e.g. ).

parse_int, if specified, will be called with the string of every JSON int
to be decoded. By default, this is equivalent to . This can
be used to use another datatype or parser for JSON integers
(e.g. ).

parse_constant, if specified, will be called with one of the following
strings: , , .
This can be used to raise an exception if invalid JSON numbers
are encountered.

If strict is false ( is the default), then control characters
will be allowed inside strings. Control characters in this context are
those with character codes in the 0–31 range, including (tab),
, and .

If the data being deserialized is not a valid JSON document, a
will be raised.

(s)

Return the Python representation of s (a instance
containing a JSON document).

will be raised if the given JSON document is not
valid.

(s)

Decode a JSON document from s (a beginning with a
JSON document) and return a 2-tuple of the Python representation
and the index in s where the document ended.

This can be used to decode a JSON document from a string that may have
extraneous data at the end.

And some basic terminology …

  • JSON exists as a string — a sequence (or series) of bytes. To convert a complex object (say a dictionary) in to a JSON representation, the object needs to be encoded as a “series of bytes”, for easy transmission or streaming — a process known as serialization.
  • Deserialization is the reverse of serialization. It involves decoding data received in JSON format as native data types, that can be manipulated further.

Why JSON?

  • Compared to its predecessor in server-client communication, XML, JSON is much smaller, translating into faster data transfers, and better experiences.
  • JSON exists as a “sequence of bytes” which is very useful in the case we need to transmit (stream) data over a network.
  • JSON is also extremely human-friendly since it is textual, and simultaneously machine-friendly.
  • JSON has expressive syntax for representing arrays, objects, numbers and booleans.

Working with Simple Built-in Datatypes

Generally, the module encodes Python objects as JSON strings implemented by the class, and decodes JSON strings into Python objects using the class.

Overview of JSON Serialization class JSONEncoder

JSONEncoder class is used for serialization of any Python object while performing encoding. It contains three different methods of encoding which are

  • default(o) – Implemented in the subclass and return serialize object for o object.
  • encode(o) – Same as json.dumps() method return JSON string of Python data structure.
  • iterencode(o) – Represent string one by one and encode object o.

With the help of encode() method of JSONEncoder class, we can also encode any Python object.

# import JSONEncoder class from json
from json.encoder import JSONEncoder
colour_dict = { "colour": }
# directly called encode method of JSON
JSONEncoder().encode(colour_dict)

Output:

'{"colour": }'

Сохранение данных в файл Pickle.

Модуль Pickle работает со структурами данных. Давайте создадим одну.

>>> shell 1                                                                 ①>>> entry = {}                                                              ②>>> entry’title’ = ‘Dive into history, 2009 edition’>>> entry’article_link’ = ‘http://diveintomark.org/archives/2009/03/27/dive-into-history-2009-edition’>>> entry’comments_link’ = None>>> entry’internal_id’ = b’\xDE\xD5\xB4\xF8′>>> entry’tags’ = (‘diveintopython’, ‘docbook’, ‘html’)>>> entry’published’ = True>>> import time>>> entry’published_date’ = time.strptime(‘Fri Mar 27 22:20:42 2009′)     ③>>> entry’published_date’ time.struct_time(tm_year=2009, tm_mon=3, tm_mday=27, tm_hour=22, tm_min=20, tm_sec=42, tm_wday=4, tm_yday=86, tm_isdst=-1)

① Все дальнейшее происходит в консоли Python #1.

② Идея в том чтобы создать словарь, который будет представлять что-нибудь полезное, например элемент рассылки Atom. Также я хочу быть уверенным, что он содержит несколько разных типов данных, чтобы раскрыть возможности модуля pickle. Не вчитывайтесь слишком сильно в эти переменные.

③ Модуль time содержит структуру данных (struct_time) для представления момента времени (вплоть до миллисекунд) и функции для работы с этими структурами. Функция strptime() принимает на вход форматированную строку и преобразует ее в struct_time. Эта строка в стандартном формате, но вы можете контролировать ее при помощи кодов форматирования. Для более подробного описания загляните в модуль time.

Теперь у нас есть замечательный словарь. Давайте сохраним его в файл.

>>> shell                                    ①1>>> import pickle>>> with open(‘entry.pickle’, ‘wb’) as f:    ②
…     pickle.dump(entry, f)                ③

① Мы все еще в первой консоли

② Используйте функцию open() для того чтобы открыть файл. Установим режим работы с файлом в ‘wb’ для того чтобы открыть файл для записи в двоичном режиме. Обернем его в конструкцию with для того чтобы быть уверенным в том что файл закроется автоматически, когда вы завершите работу с ним.

③ Функция dump() модуля pickle принимает сериализуемую структуру данных Python, сериализует ее в двоичный, Python-зависимый формат использует последнюю версию протокола pickle и сохраняет ее в открытый файл.

Последнее предложение было очень важным.

  • Протокол pickle зависит от Python; здесь нет гарантий совместимости с другими языками. Вы возможно не сможете взять entry.pickle файл, который только что сделали и как — либо с пользой его использовать при помощи Perl, PHP, Java или любого другого языка программирования
  • Не всякая структура данных Python может быть сериализована модулем Pickle. Протокол pickle менялся несколько раз с добавлением новых типов данных в язык Python, и все еще у него есть ограничения.
  • Как результат, нет гарантии совместимости между разными версиями Python. Новые версии Python поддерживают старые форматы сериализации, но старые версии Python не поддерживают новые форматы (поскольку не поддерживают новые форматы данных)
  • Пока вы не укажете иное, функции модуля pickle будут использовать последнюю версию протокола pickle. Это сделано для уверенности в том, что вы имеете наибольшую гибкость в типах данных, которые вы можете сериализовать, но это также значит, что результирующий файл будет невозможно прочитать при помощи старых версий Python, которые не поддерживают последнюю версию протокола pickle.
  • Последняя версия протокола pickle это двоичный формат. Убедитесь, что открываете файлы pickle в двоичном режиме, или данные будут повреждены при записи.
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector