Функция load() модуля json в python

Standard Compliance and Interoperability¶

The JSON format is specified by RFC 7159 and by
ECMA-404.
This section details this module’s level of compliance with the RFC.
For simplicity, and subclasses, and
parameters other than those explicitly mentioned, are not considered.

This module does not comply with the RFC in a strict fashion, implementing some
extensions that are valid JavaScript but not valid JSON. In particular:

  • Infinite and NaN number values are accepted and output;

  • Repeated names within an object are accepted, and only the value of the last
    name-value pair is used.

Since the RFC permits RFC-compliant parsers to accept input texts that are not
RFC-compliant, this module’s deserializer is technically RFC-compliant under
default settings.

Character Encodings

The RFC requires that JSON be represented using either UTF-8, UTF-16, or
UTF-32, with UTF-8 being the recommended default for maximum interoperability.

As permitted, though not required, by the RFC, this module’s serializer sets
ensure_ascii=True by default, thus escaping the output so that the resulting
strings only contain ASCII characters.

Other than the ensure_ascii parameter, this module is defined strictly in
terms of conversion between Python objects and
, and thus does not otherwise directly address
the issue of character encodings.

The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text,
and this module’s serializer does not add a BOM to its output.
The RFC permits, but does not require, JSON deserializers to ignore an initial
BOM in their input. This module’s deserializer raises a
when an initial BOM is present.

The RFC does not explicitly forbid JSON strings which contain byte sequences
that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16
surrogates), but it does note that they may cause interoperability problems.
By default, this module accepts and outputs (when present in the original
) code points for such sequences.

Infinite and NaN Number Values

The RFC does not permit the representation of infinite or NaN number values.
Despite that, by default, this module accepts and outputs ,
, and as if they were valid JSON number literal values:

>>> # Neither of these calls raises an exception, but the results are not valid JSON
>>> json.dumps(float('-inf'))
'-Infinity'
>>> json.dumps(float('nan'))
'NaN'
>>> # Same when deserializing
>>> json.loads('-Infinity')
-inf
>>> json.loads('NaN')
nan

In the serializer, the allow_nan parameter can be used to alter this
behavior. In the deserializer, the parse_constant parameter can be used to
alter this behavior.

Repeated Names Within an Object

The RFC specifies that the names within a JSON object should be unique, but
does not mandate how repeated names in JSON objects should be handled. By
default, this module does not raise an exception; instead, it ignores all but
the last name-value pair for a given name:

>>> weird_json = '{"x": 1, "x": 2, "x": 3}'
>>> json.loads(weird_json)
{'x': 3}

The object_pairs_hook parameter can be used to alter this behavior.

Top-level Non-Object, Non-Array Values

The old version of JSON specified by the obsolete RFC 4627 required that
the top-level value of a JSON text must be either a JSON object or array
(Python or ), and could not be a JSON null,
boolean, number, or string value. RFC 7159 removed that restriction, and
this module does not and has never implemented that restriction in either its
serializer or its deserializer.

Regardless, for maximum interoperability, you may wish to voluntarily adhere
to the restriction yourself.

dumps¶

(obj, sort_keys=None, cls=<class ‘json_tricks.encoders.TricksEncoder’>, obj_encoders=, extra_obj_encoders=(), primitives=False, compression=None, allow_nan=False, conv_str_byte=False, fallback_encoders=(), **jsonkwargs)

Convert a nested data structure to a json string.

Parameters:
  • obj – The Python object to convert.
  • sort_keys – Keep this False if you want order to be preserved.
  • cls – The json encoder class to use, defaults to NoNumpyEncoder which gives a warning for numpy arrays.
  • obj_encoders – Iterable of encoders to use to convert arbitrary objects into json-able promitives.
  • extra_obj_encoders – Like obj_encoders but on top of them: use this to add encoders without replacing defaults. Since v3.5 these happen before default encoders.
  • fallback_encoders – These are extra obj_encoders that 1) are ran after all others and 2) only run if the object hasn’t yet been changed.
  • allow_nan – Allow NaN and Infinity values, which is a (useful) violation of the JSON standard (default False).
  • conv_str_byte – Try to automatically convert between strings and bytes (assuming utf-8) (default False).
Returns:

The string containing the json-encoded version of obj.

Other arguments are passed on to cls. Note that sort_keys should be false if you want to preserve order.

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.

numpy scalars¶

It’s not possible (without a lot of hacks) to encode numpy scalars. This is the case because some numpy scalars (float64, and depending on Python version also int64) are subclasses of float and int. This means that the Python json encoder will stringify them without them ever reaching the custom encoders.

So if you really want to encode numpy scalars, you’ll have to do the conversion beforehand. For that purpose you can use encode_scalars_inplace, which mutates a nested data structure (in place!) to replace any numpy scalars by their representation. If you serialize this result, it can subsequently be loaded without further adaptations.

It’s not great, but unless the Python json module changes, it’s the best that can be done. See issue 18 for more details.

(obj)

Searches a data structure of lists, tuples and dicts for numpy scalars
and replaces them by their dictionary representation, which can be loaded
by json-tricks. This happens in-place (the object is changed, use a copy).

Простой пример в JSON

В следующем примере показано, как использовать JSON для хранения информации, связанной с книгами, в зависимости от их темы и издания.

{
   "book": 
}

После понимания вышеупомянутой программы мы попробуем другой пример. Давайте сохраним код ниже как json.htm

<html>
   <head>
      <title>JSON example</title>
      <script language = "javascript" >
         var object1 = { "language" : "Java", "author"  : "herbert schildt" };
         document.write("<h1>JSON with JavaScript example</h1>");
         document.write("<br>");
         document.write("<h3>Language = " + object1.language+"</h3>");  
         document.write("<h3>Author = " + object1.author+"</h3>");   

         var object2 = { "language" : "C++", "author"  : "E-Balagurusamy" };
         document.write("<br>");
         document.write("<h3>Language = " + object2.language+"</h3>");  
         document.write("<h3>Author = " + object2.author+"</h3>");   
  
         document.write("<hr />");
         document.write(object2.language + " programming language can be studied " + "from book written by " + object2.author);
         document.write("<hr />");
      </script>
   </head>
   
   <body>
   </body>
</html>

Теперь давайте попробуем открыть json.htm с помощью IE или любого другого браузера с поддержкой javascript, который выдает следующий результат:

Вы можете обратиться к главе «Объекты JSON» для получения дополнительной информации об объектах JSON.

JSON — Синтаксис

Давайте кратко рассмотрим основной синтаксис JSON. Синтаксис JSON в основном рассматривается как подмножество синтаксиса JavaScript; это включает в себя следующее —

  • Данные представлены в парах имя / значение.

  • В фигурных скобках хранятся объекты, и за каждым именем следует ‘:’ (двоеточие), пары имя / значение разделяются (запятая).

  • Квадратные скобки содержат массивы, а значения разделяются, (запятая).

Ниже приведен простой пример —

{
   "book": 
}

JSON поддерживает следующие две структуры данных —

  • Коллекция пар имя / значение — эта структура данных поддерживается различными языками программирования.

  • Упорядоченный список значений — включает массив, список, вектор или последовательность и т. Д.

JSON — DataTypes

Формат JSON поддерживает следующие типы данных —

Sr.No. Тип и описание
1

номер

формат с плавающей точкой двойной точности в JavaScript

2

строка

Unicode с двойными кавычками с обратной косой чертой

3

логический

правда или ложь

4

массив

упорядоченная последовательность значений

5

Значение

это может быть строка, число, истина или ложь, null т. д.

6

объект

неупорядоченный набор пар ключ: значение

7

Пробелы

может использоваться между любой парой токенов

8

null

опорожнить

Разбираем JSON-данные в Python

Если мы хотим выполнить обратную операцию и быстро раскодировать формат JSON средствами языка Python, нам поможет метод loads. Он позволяет без труда преобразовать JSON в объект, и с этим объектом мы сможем легко взаимодействовать в программе.

import json
jsonData = """ {
    "ID"       : 310450,
    "login"    : "admin",
    "name"     : "James Bond",
    "password" : "root",
    "phone"    : 3330303,
    "email"    : " bond@mail.com",
    "online"   : true
} """
dictData = json.loads(jsonData)
print(dictData"name"])
print(dictData"phone"])
print(dictData"email"])
print(dictData"online"])

James Bond
3330303
bond@mail.com 
True

Мы видим, что произошло обратное, а литерал true автоматически преобразовался в True. Это произошло, чтобы была возможность работать с ним средствами Python.

P.S. Итак, мы выполнили кодирование и декодирование информации в JSON-формате с помощью встроенных средств Python. Благодаря наличию удобных методов из модуля json (dumps и loads), эти операции были осуществлены довольно просто. Остаётся добавить, что функции loads и dumps способны взаимодействовать и с другими видами объектов, включая более сложные (например, со вложенными разновидностями словарей со множеством строковых значений).

Packaging

rustup default nightly
pip wheel --no-binary=orjson orjson

This is an example of building a wheel using the repository as source,
installed from upstream, and a pinned version of Rust:

pip install maturin
curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain nightly-2021-03-25 --profile minimal -y
maturin build --no-sdist --release --strip --manylinux off
ls -1 target/wheels

Problems with the Rust nightly channel may require pinning a version.
is known to be ok.

orjson is tested for amd64 and aarch64 on Linux, macOS, and Windows. It
may not work on 32-bit targets. It has recommended
specified in so it is recommended to either not set
or include these options.

There are no runtime dependencies other than libc.

orjson’s tests are included in the source distribution on PyPI. It is
necessarily to install dependencies from PyPI specified in
. These require a C compiler. The tests do not
make network requests.

The tests should be run as part of the build. It can be run like this:

pip install -r test/requirements.txt
pytest -q test

Date, time, datetime and timedelta¶

Date, time, datetime and timedelta objects are stored as dictionaries of “day”, “hour”, “millisecond” etc keys, for each nonzero property.

Timezone name is also stored in case it is set. You’ll need to have installed to use timezone-aware date/times, it’s not needed for naive date/times.

{
        "__datetime__" null,
        "year" 1988,
        "month" 3,
        "day" 15,
        "hour" 8,
        "minute" 3,
        "second" 59,
        "microsecond" 7,
        "tzinfo" "Europe/Amsterdam"
}

This approach was chosen over timestamps for readability and consistency between date and time, and over a single string to prevent parsing problems and reduce dependencies. Note that if , date/times are encoded as ISO 8601, but they won’t be restored automatically.

Command Line Interface¶

Source code: Lib/json/tool.py

The module provides a simple command line interface to validate
and pretty-print JSON objects.

If the optional and arguments are not
specified, and will be used respectively:

$ 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)

Changed in version 3.5: The output is now in the same order as the input. Use the
option to sort the output of dictionaries
alphabetically by key.

Command line options

The JSON file to be validated or pretty-printed:

$ 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
    }

If infile is not specified, read from .

Write the output of the infile to the given outfile. Otherwise, write it
to .

Sort the output of dictionaries alphabetically by key.

New in version 3.5.

Disable escaping of non-ascii characters, see for more information.

New in version 3.9.

Parse every input line as separate JSON object.

New in version 3.8.

Mutually exclusive options for whitespace control.

New in version 3.9.

Show the help message.

Footnotes

As noted in the errata for RFC 7159,
JSON permits literal U+2028 (LINE SEPARATOR) and
U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript
(as of ECMAScript Edition 5.1) does not.

Пример десериализации 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, теперь он под вашим контролем. Но что вы будете делать с этой силой — остается за вами. Вы можете кормить его, выращивать, и даже научить новым приемам. Не то чтобы я не доверяю вам, но держите его на привязи, хорошо?

Расшифровка JSON на Java

В следующем примере используются JSONObject и JSONArray, где JSONObject — это java.util.Map, а JSONArray — это java.util.List, поэтому вы можете обращаться к ним с помощью стандартных операций Map или List.

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;

class JsonDecodeDemo {

   public static void main(String[] args) {
	
      JSONParser parser = new JSONParser();
      String s = "}}}}]";
		
      try{
         Object obj = parser.parse(s);
         JSONArray array = (JSONArray)obj;
			
         System.out.println("The 2nd element of array");
         System.out.println(array.get(1));
         System.out.println();

         JSONObject obj2 = (JSONObject)array.get(1);
         System.out.println("Field \"1\"");
         System.out.println(obj2.get("1"));    

         s = "{}";
         obj = parser.parse(s);
         System.out.println(obj);

         s = "";
         obj = parser.parse(s);
         System.out.println(obj);

         s = "";
         obj = parser.parse(s);
         System.out.println(obj);
      }catch(ParseException pe) {
		
         System.out.println("position: " + pe.getPosition());
         System.out.println(pe);
      }
   }
}

При компиляции и выполнении вышеуказанной программы будет получен следующий результат:

The 2nd element of array
{"1":{"2":{"3":{"4":}}}}

Field "1"
{"2":{"3":{"4":}}}
{}


JSON с Ajax

AJAX — это асинхронный JavaScript и XML, который используется на стороне клиента как группа взаимосвязанных методов веб-разработки для создания асинхронных веб-приложений. Согласно модели AJAX, веб-приложения могут отправлять и извлекать данные с сервера асинхронно, не влияя на отображение и поведение существующей страницы.

Многие разработчики используют JSON для передачи обновлений AJAX между клиентом и сервером. В качестве примера AJAX можно рассматривать сайты, обновляющие результаты спортивных матчей. Если эти оценки должны быть обновлены на веб-сайте, они должны храниться на сервере, чтобы веб-страница могла получать оценку, когда это требуется. Здесь мы можем использовать данные в формате JSON.

Любые данные, которые обновляются с использованием AJAX, могут храниться в формате JSON на веб-сервере. AJAX используется для того, чтобы javascript мог при необходимости извлекать эти файлы JSON, анализировать их и выполнять одну из следующих операций:

  • Сохраните проанализированные значения в переменных для дальнейшей обработки, прежде чем отображать их на веб-странице.

  • Он напрямую назначает данные элементам DOM на веб-странице, чтобы они отображались на веб-сайте.

JSON-Encoder.

Синтаксис:

import json

json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, 
              check_circular=True, allow_nan=True, 
              sort_keys=False, indent=None, 
              separators=None, default=None)

Параметры:

  • — игнорирование не базовых типов ключей в словарях,
  • — экранирование не-ASSCI символов,
  • — проверка циклических ссылок,
  • — представление значений , , в JSON,
  • — сортировка словарей,
  • — количество отступов при сериализации,
  • — разделители используемые в JSON,
  • — метод подкласса для объектов, которые не могут быть сериализованы,

Описание:

Функция модуля расширяет возможности преобразование структур данных Python в формат JSON.

Поддерживает следующие объекты и типы по умолчанию:

Python JSON

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

Если аргумент имеет значение (по умолчанию), то вызывается для попытки преобразования ключей, которые не являются , , или . Если имеет значение , такие элементы просто пропускаются.

Если аргумент имеет значение (по умолчанию), на выходе гарантированно все входящие не ASCII символы будут экранированы последовательностями \uXXXX. Если имеет значение , то не ASCII символы будут выводиться как есть.

Если аргумент (по умолчанию), тогда списки, словари и самостоятельно закодированные объекты будут проверяться на циклические ссылки во время кодировки, чтобы предотвратить бесконечную рекурсию, что может вызвать исключение . В другом случае, такая проверка не выполняется.

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

Если аргумент (по умолчанию: False), выводимый словарь будет отсортирован по именам ключей, что полезно для регрессивного тестирования.

Если аргумент является неотрицательным целым числом или строкой, то вложенные объекты и массивы JSON будут выводиться с этим количеством отступов. Если уровень отступа равен 0, отрицательный или является пустой строкой , будут использоваться новые строки без отступов. Если (по умолчанию), то на выходе JSON будет наиболее компактным. Если будет строкой типа , то это значение будет использоваться в качестве отступа.

Если указан аргумент , то он должен быть кортежем типа . По умолчанию используется если . Для получения наиболее компактного представления JSON следует использовать , чтобы уменьшить количество пробелов.

Значение должно быть методом подкласса . Он вызывается для объектов, которые не могут быть сериализованы. Метод должен вернуть кодируемую версию объекта JSON или вызывать исключение . Если аргумент не указан и какой-то из объектов не может быть преобразован в JSON, то возникает ошибка .

Методы класса .

Реализует метод в подклассе так, чтобы он возвращал сериализуемый объект для или вызывал базовую реализацию.

Например, чтобы поддерживать произвольные итераторы, вы можете реализовать метод следующим образом:

def default(self, obj):
   try
       iterable = iter(obj)
   except TypeError
       pass
   else
       return list(iterable)
   # базовый класс вызывает исключение TypeError
   return json.JSONEncoder.default(self, obj)

Возвращает строковое представление JSON структуры данных Python.

json.JSONEncoder().encode({"foo" \"bar", "baz"\]})
'{"foo": \}'

Преобразовывает переданный объект o и выдаёт каждое строковое представление, как только оно становится доступным. Например:

for chunk in json.JSONEncoder().iterencode(bigobject):
    mysocket.write(chunk)

Примеры использования:

>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
...     def default(self, obj):
...         if isinstance(obj, complex):
...             return obj.real, obj.imag
...         # Let the base class default method raise the TypeError
...         return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
# ''
>>> ComplexEncoder().encode(2 + 1j)
# ''
>>> list(ComplexEncoder().iterencode(2 + 1j))
# ']

Complex JSON object decoding in Python

To decode complex object in JSON, use an object_hook parameter which checks JSON string contains the complex object or not. Lets understand with string to JSON Python Example,

import json
  # function check JSON string contains complex object
  def is_complex(objct):
    if '__complex__' in objct:
      return complex(objct, objct)
    return objct
  
  # use of json loads method with object_hook for check object complex or not
  complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook = is_complex)
  #here we not passed complex object so it's convert into dictionary
  simple_object =json.loads('{"real": 6, "img": 7}', object_hook = is_complex)
  print("Complex_object......",complex_object)
  print("Without_complex_object......",simple_object)

Output:

Complex_object...... (4+5j)
Without_complex_object...... {'real': 6, 'img': 7}
Добавить комментарий

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

Adblock
detector