Парсинг json в python

Library Version¶

The Jansson version is of the form A.B.C, where A is the major
version, B is the minor version and C is the micro version. If the
micro version is zero, it’s omitted from the version string, i.e. the
version string is just A.B.

When a new release only fixes bugs and doesn’t add new features or
functionality, the micro version is incremented. When new features are
added in a backwards compatible way, the minor version is incremented
and the micro version is set to zero. When there are backwards
incompatible changes, the major version is incremented and others are
set to zero.

The following preprocessor constants specify the current version of
the library:

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 recommends 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 will ignore an initial BOM, if
present.

Changed in version 3.6.0: Older versions would raise 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
) codepoints 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}
True

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.

Encode and Write JSON data to a file using json.dump()

We can use it in the following cases.

  • To write the JSON response in a file: Most of the time, when you execute a GET request, you receive a response in JSON format, and you can store JSON response in a file for future use or for an underlying system to use.
  • For example, you have data in a list or dictionary or any Python object, and you want to encode and store it in a file in the form of JSON.

In this example, we are going to convert the Python dictionary into a JSON format and write it into a file.

Output:

Started writing JSON data into a file
Done writing JSON data into developerDetail.json file


File after writing JSON encoded data using Python

Write Indented and pretty printed JSON data into a file using the dump method

If the user wants to read JSON file so it must be readable and well organized, so whosever consumes this will have a better understanding of a structure of a data. The dump() method provides the following arguments to pretty-print JSON data.

  • The indent parameter specifies the spaces that are used at the beginning of a line.
  • The separator argument of a json.dump method you can specify any separator between key and value.
  • The to sort JSON data by keys.

Let’s see how to write pretty-printed JSON data into a file.

Output:

Done writing pretty printed JSON data into a file


File after writing prettyprinted JSON data

Read More

Compact encoding to save file space by changing JSON key-value separator

If you are are not reading a file, but you only need to write JSON data into a file to use by the underlying system or application, then you can write JSON data into a file by doing compact encoding.

We can write JSON data into a file by changing JSON key-value separator. You can change JSON representation as per your needs. Using the separator argument of a method you can specify any separator between key and value.

To limit the JSON file size we can remove extra spacing between JSON key-value. I have decided to do the compact encoding (). Using this separator we can remove the whitespaces from JSON to make the JSON more compact and save bytes from being sent via HTTP. Now, Let see the example.

Output:

Started writing compact JSON data into a file
Done writing compact JSON data into .json file

File content:

{"name":"jane doe","salary":9000,"skills":,"companies":,"email":"JaneDoe@pynative.com"}

Skip nonbasic types while writing JSON into a file using parameter

The built-in json module of Python can only handle Python primitives types that have a direct JSON equivalent (e.g., dictionary, lists, strings, ints, None, etc.).

If Python dictionary contains a custom Python object as one of the keys and if we try to convert it into a JSON format, you will get a TypeError i.e., .

If this custom object isn’t required in JSON data, you can skip it using a argument of the method.
If is True, then keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

If it is necessary to convert it into JSON, then you can refer to our article on how to Make Python class JSON Serializable.

Now, Let’s see the example.

Output:

Writing JSON data into file by skipping non-basic types
Done


JSON file after skipping on-basic types

As you can see in the JSON output the object is skipped.

Handle non-ASCII characters from JSON data while writing it into a file

The method has  parameter. The  is by-default true. The output is guaranteed to have all incoming non-ASCII characters escaped. If  is false, these characters will be output as-is. If you want to store non-ASCII characters, as-is use the following code.

Output:

unicode String is  ø
JSON character encoding by setting ensure_ascii=False
"ø"

Also, read the Complete Guide on Encode and Decode Unicode data into JSON using Python.

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.

All done!

Congratulations, you can now wield the mighty power of JSON for any and all of your nefarious Python needs.

While the examples you’ve worked with here are certainly contrived and overly simplistic, they illustrate a workflow you can apply to more general tasks:

  1. Import the package.
  2. Read the data with or .
  3. Process the data.
  4. Write the altered data with or .

What you do with your data once it’s been loaded into memory will depend on your use case. Generally, your goal will be gathering data from a source, extracting useful information, and passing that information along or keeping a record of it.

Today you took a journey: you captured and tamed some wild JSON, and you made it back in time for supper! As an added bonus, learning the package will make learning and a snap.

Пример десериализации 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?

Информация в формате JSON может быть представлена в двух видах:

  • Последовательность пар с ключами и соответствующими им значениями;
  • Просто упорядоченный набор значений.

Как правило, любой высокоуровневый язык программирования поддерживает эти структуры данных. Значения, которые передаются в JSON, могут являться объектами, строками, числами, одномерными массивами, а также литералами (true, false, null). Python поддерживает работу с форматом JSON, благодаря модулю json и методам по кодированию и декодированию данных. Это позволяет легко получать и отправлять информацию в комфортном для чтения виде.

Decoding¶

This sections describes the functions that can be used to decode JSON
text to the Jansson representation of JSON data. The JSON
specification requires that a JSON text is either a serialized array
or object, and this requirement is also enforced with the following
functions. In other words, the top level value in the JSON text being
decoded must be either array or object.

See for a discussion on Jansson’s conformance
to the JSON specification. It explains many design decisions that
affect especially the behavior of the decoder.

Each function takes a flags parameter that can be used to control
the behavior of the decoder. Its default value is 0. The following
macros can be ORed together to obtain flags.

JSON_REJECT_DUPLICATES

Issue a decoding error if any JSON object in the input text
contains duplicate keys. Without this flag, the value of the last
occurence of each key ends up in the result. Key equivalence is
checked byte-by-byte, without special Unicode comparison
algorithms.

New in version 2.1.

JSON_DISABLE_EOF_CHECK

By default, the decoder expects that its whole input constitutes a
valid JSON text, and issues an error if there’s extra data after
the otherwise valid JSON input. With this flag enabled, the decoder
stops after decoding a valid JSON array or object, and thus allows
extra data after the JSON text.

New in version 2.1.

The following functions perform the actual JSON decoding.

*json_loads(const char *input, size_t flags,  *error)
Return value: New reference.

Decodes the JSON string input and returns the array or object it
contains, or NULL on error, in which case error is filled with
information about the error. flags is described above.

*json_loadb(const char *buffer, size_t buflen, size_t flags,  *error)
Return value: New reference.

Decodes the JSON string buffer, whose length is buflen, and
returns the array or object it contains, or NULL on error, in
which case error is filled with information about the error. This
is similar to except that the string doesn’t
need to be null-terminated. flags is described above.

New in version 2.1.

*json_loadf(FILE *input, size_t flags,  *error)
Return value: New reference.

Decodes the JSON text in stream input and returns the array or
object it contains, or NULL on error, in which case error is
filled with information about the error. flags is described
above.

This function will start reading the input from whatever position
the input file was, without attempting to seek first. If an error
occurs, the file position will be left indeterminate. On success,
the file position will be at EOF, unless JSON_DISABLE_EOF_CHECK
flag was used. In this case, the file position will be at the first
character after the last or } in the JSON input. This
allows calling on the same FILE object
multiple times, if the input consists of consecutive JSON texts,
possibly separated by whitespace.

Основы

json.dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) — сериализует obj как форматированный JSON поток в fp.

Если skipkeys = True, то ключи словаря не базового типа (str, unicode, int, long, float, bool, None) будут проигнорированы, вместо того, чтобы вызывать исключение TypeError.

Если ensure_ascii = True, все не-ASCII символы в выводе будут экранированы последовательностями \uXXXX, и результатом будет строка, содержащая только ASCII символы. Если ensure_ascii = False, строки запишутся как есть.

Если check_circular = False, то проверка циклических ссылок будет пропущена, а такие ссылки будут вызывать OverflowError.

Если allow_nan = False, при попытке сериализовать значение с запятой, выходящее за допустимые пределы, будет вызываться ValueError (nan, inf, -inf) в строгом соответствии со спецификацией JSON, вместо того, чтобы использовать эквиваленты из JavaScript (NaN, Infinity, -Infinity).

Если indent является неотрицательным числом, то массивы и объекты в JSON будут выводиться с этим уровнем отступа. Если уровень отступа 0, отрицательный или «», то вместо этого будут просто использоваться новые строки. Значение по умолчанию None отражает наиболее компактное представление. Если indent — строка, то она и будет использоваться в качестве отступа.

Если sort_keys = True, то ключи выводимого словаря будут отсортированы.

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) — сериализует obj в строку JSON-формата.

Аргументы имеют то же значение, что и для dump().

Ключи в парах ключ/значение в JSON всегда являются строками. Когда словарь конвертируется в JSON, все ключи словаря преобразовываются в строки. В результате этого, если словарь сначала преобразовать в JSON, а потом обратно в словарь, то можно не получить словарь, идентичный исходному. Другими словами, loads(dumps(x)) != x, если x имеет нестроковые ключи.

json.load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) — десериализует JSON из fp.

object_hook — опциональная функция, которая применяется к результату декодирования объекта (dict). Использоваться будет значение, возвращаемое этой функцией, а не полученный словарь.

object_pairs_hook — опциональная функция, которая применяется к результату декодирования объекта с определённой последовательностью пар ключ/значение. Будет использован результат, возвращаемый функцией, вместо исходного словаря. Если задан так же object_hook, то приоритет отдаётся object_pairs_hook.

parse_float, если определён, будет вызван для каждого значения JSON с плавающей точкой. По умолчанию, это эквивалентно float(num_str).

parse_int, если определён, будет вызван для строки JSON с числовым значением. По умолчанию эквивалентно int(num_str).

parse_constant, если определён, будет вызван для следующих строк: «-Infinity», «Infinity», «NaN». Может быть использовано для возбуждения исключений при обнаружении ошибочных чисел JSON.

Если не удастся десериализовать JSON, будет возбуждено исключение ValueError.

json.loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) — десериализует s (экземпляр str, содержащий документ JSON) в объект Python.

Кодировщики и декодировщики

Класс json.JSONDecoder(object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None) — простой декодер JSON.

Выполняет следующие преобразования при декодировании:

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

Он также понимает NaN, Infinity, и -Infinity как соответствующие значения float, которые находятся за пределами спецификации JSON.

Класс json.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Расширяемый кодировщик JSON для структур данных Python. Поддерживает следующие объекты и типы данных по умолчанию:

Python JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null

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.

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.

Чтение¶

Файл sw_templates.json:

{
  "access" 
    "switchport mode access",
    "switchport access vlan",
    "switchport nonegotiate",
    "spanning-tree portfast",
    "spanning-tree bpduguard enable"
  ],
  "trunk" 
    "switchport trunk encapsulation dot1q",
    "switchport mode trunk",
    "switchport trunk native vlan 999",
    "switchport trunk allowed vlan"
  
}

Для чтения в модуле json есть два метода:

  • json.load() — метод считывает файл в формате JSON и возвращает объекты Python
  • json.loads() — метод считывает строку в формате JSON и возвращает объекты Python

json.load()

Чтение файла в формате JSON в объект Python (файл json_read_load.py):

import json

with open('sw_templates.json') as f
    templates = json.load(f)

print(templates)

for section, commands in templates.items():
    print(section)
    print('\n'.join(commands))

Вывод будет таким:

$ python json_read_load.py
{'access': , 'trunk': }
access
switchport mode access
switchport access vlan
switchport nonegotiate
spanning-tree portfast
spanning-tree bpduguard enable
trunk
switchport trunk encapsulation dot1q
switchport mode trunk
switchport trunk native vlan 999
switchport trunk allowed vlan

19.2.5. 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.

19.2.5.1. 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.

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.

기본 사용법¶

(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

이 를 사용하여 obj를 JSON 형식 스트림으로 fp(를 지원하는 )로 직렬화합니다.

skipkeys가 참이면 (기본값: ), 기본형(, , , , )이 아닌 딕셔너리 키는 를 발생시키는 대신 건너뜁니다.

모듈은 항상 객체가 아니라 객체를 생성합니다. 따라서, 는 입력을 지원해야 합니다.

ensure_ascii가 참(기본값)이면, 출력에서 모든 비 ASCII 문자가 이스케이프 되도록 보장됩니다. ensure_ascii가 거짓이면, 그 문자들은 있는 그대로 출력됩니다.

check_circular가 거짓이면 (기본값: ), 컨테이너형에 대한 순환 참조 검사를 건너뛰고 순환 참조는 를 일으킵니다 (또는 더 나빠질 수 있습니다).

allow_nan이 거짓이면 (기본값: ), JSON 사양을 엄격히 준수하여 범위를 벗어난 값(, , )을 직렬화하면 를 일으킵니다. allow_nan이 참이면, JavaScript의 대응 물(, , )이 사용됩니다.

indent가 음이 아닌 정수나 문자열이면, JSON 배열 요소와 오브젝트 멤버가 해당 들여쓰기 수준으로 예쁘게 인쇄됩니다. 0, 음수 또는 의 들여쓰기 수준은 줄 넘김만 삽입합니다. (기본값)은 가장 간결한(compact) 표현을 선택합니다. 양의 정수 indent를 사용하면, 수준 당 그만큼의 스페이스로 들여쓰기합니다. indent가 문자열이면 (가령 ), 각 수준을 들려 쓰는 데 그 문자열을 사용합니다.

버전 3.2에서 변경: indent에 정수뿐만 아니라 문자열을 허용합니다.

지정되면, separators는 튜플이어야 합니다. 기본값은 indent가 이면 이고, 그렇지 않으면 입니다. 가장 간결한 JSON 표현을 얻으려면, 를 지정하여 공백을 제거해야 합니다.

버전 3.4에서 변경: indent가 이 아니면, 를 기본값으로 사용합니다.

지정되면, default는 달리 직렬화할 수 없는 객체에 대해 호출되는 함수여야 합니다. 객체의 JSON 인코딩 가능한 버전을 반환하거나 를 발생시켜야 합니다. 지정하지 않으면, 가 발생합니다.

sort_keys가 참이면 (기본값: ), 딕셔너리의 출력이 키로 정렬됩니다.

사용자 정의 서브 클래스(예를 들어, 메서드를 재정의하여 추가 형을 직렬화하는 것)를 사용하려면, cls 키워드 인자로 지정하십시오; 그렇지 않으면 가 사용됩니다.

버전 3.6에서 변경: 모든 선택적 매개 변수는 이제 입니다.

참고

과 과 달리, JSON은 프레임 프로토콜이 아니므로 같은 fp를 사용하여 를 반복 호출하여 여러 객체를 직렬화하려고 하면 잘못된 JSON 파일이 생성됩니다.

(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

이 를 사용하여 obj를 JSON 형식의 로 직렬화합니다. 인자는 에서와 같은 의미입니다.

참고

JSON의 키/값 쌍에 있는 키는 항상 형입니다. 딕셔너리를 JSON으로 변환하면, 딕셔너리의 모든 키가 문자열로 강제 변환됩니다. 이것의 결과로, 딕셔너리를 JSON으로 변환한 다음 다시 딕셔너리로 변환하면, 딕셔너리가 원래의 것과 같지 않을 수 있습니다. 즉, x에 비 문자열 키가 있으면 입니다.

(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)

이 를 사용하여 fp(JSON 문서를 포함하는 를 지원하는 이나 )를 파이썬 객체로 역 직렬화합니다.

object_hook은 모든 오브젝트 리터럴의 디코딩된 결과()로 호출되는 선택적 함수입니다. object_hook의 반환 값이 대신에 사용됩니다. 이 기능은 사용자 정의 디코더를 구현하는 데 사용할 수 있습니다 (예를 들어, JSON-RPC 클래스 힌팅(class hinting)).

object_pairs_hook은 모든 오브젝트 리터럴의 쌍의 순서 있는 목록으로 디코딩된 결과로 호출되는 선택적 함수입니다. 대신 object_pairs_hook의 반환 값이 사용됩니다. 이 기능은 사용자 정의 디코더를 구현하는 데 사용할 수 있습니다. object_hook도 정의되어 있으면, object_pairs_hook이 우선순위를 갖습니다.

버전 3.1에서 변경: object_pairs_hook에 대한 지원이 추가되었습니다.

parse_float가 지정되면, 디코딩될 모든 JSON float의 문자열로 호출됩니다. 기본적으로, 이것은 와 동등합니다. JSON float에 대해 다른 데이터형이나 구문 분석기를 사용하고자 할 때 사용될 수 있습니다 (예를 들어, ).

parse_int가 지정되면, 디코딩될 모든 JSON int의 문자열로 호출됩니다. 기본적으로 이것은 와 동등합니다. JSON 정수에 대해 다른 데이터형이나 구문 분석기를 사용하고자 할 때 사용될 수 있습니다 (예를 들어 ).

parse_constant가 지정되면, 다음과 같은 문자열 중 하나로 호출됩니다: , , . 잘못된 JSON 숫자를 만날 때 예외를 발생시키는 데 사용할 수 있습니다.

버전 3.1에서 변경: parse_constant는 더는 〈null〉, 〈true〉, 〈false’에 대해 호출되지 않습니다.

사용자 정의 서브 클래스를 사용하려면, 키워드 인자로 지정하십시오; 그렇지 않으면 가 사용됩니다. 추가 키워드 인자는 클래스 생성자에 전달됩니다.

역 직렬화되는 데이터가 유효한 JSON 문서가 아니면, 가 발생합니다.

버전 3.6에서 변경: 모든 선택적 매개 변수는 이제 입니다.

버전 3.6에서 변경: fp는 이제 이 될 수 있습니다. 입력 인코딩은 UTF-8, UTF-16 또는 UTF-32 여야 합니다.

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython Variables
Python Variables
Variable Names
Assign Multiple Values
Output Variables
Global Variables
Variable Exercises

Python Data TypesPython NumbersPython CastingPython Strings
Python Strings
Slicing Strings
Modify Strings
Concatenate Strings
Format Strings
Escape Characters
String Methods
String Exercises

Python BooleansPython OperatorsPython Lists
Python Lists
Access List Items
Change List Items
Add List Items
Remove List Items
Loop Lists
List Comprehension
Sort Lists
Copy Lists
Join Lists
List Methods
List Exercises

Python Tuples
Python Tuples
Access Tuples
Update Tuples
Unpack Tuples
Loop Tuples
Join Tuples
Tuple Methods
Tuple Exercises

Python Sets
Python Sets
Access Set Items
Add Set Items
Remove Set Items
Loop Sets
Join Sets
Set Methods
Set Exercises

Python Dictionaries
Python Dictionaries
Access Items
Change Items
Add Items
Remove Items
Loop Dictionaries
Copy Dictionaries
Nested Dictionaries
Dictionary Methods
Dictionary Exercise

Python If…ElsePython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython Classes/ObjectsPython InheritancePython IteratorsPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try…ExceptPython User InputPython String Formatting

Array¶

A JSON array is an ordered collection of other JSON values.

*json_array(void)
Return value: New reference.

Returns a new JSON array, or NULL on error. Initially, the array
is empty.

size_t json_array_size(const  *array)

Returns the number of elements in array, or 0 if array is NULL
or not a JSON array.

*json_array_get(const  *array, size_t index)
Return value: Borrowed reference.

Returns the element in array at position index. The valid range
for index is from 0 to the return value of
minus 1. If array is not a JSON array,
if array is NULL, or if index is out of range, NULL is
returned.

int json_array_set( *array, size_t index,  *value)

Replaces the element in array at position index with value.
The valid range for index is from 0 to the return value of
minus 1. Returns 0 on success and -1 on
error.

int json_array_set_new( *array, size_t index,  *value)

Like but steals the reference to value.
This is useful when value is newly created and not used after
the call.

int json_array_append( *array,  *value)

Appends value to the end of array, growing the size of array
by 1. Returns 0 on success and -1 on error.

int json_array_append_new( *array,  *value)

Like but steals the reference to
value. This is useful when value is newly created and not used
after the call.

int json_array_insert( *array, size_t index,  *value)

Inserts value to array at position index, shifting the
elements at index and after it one position towards the end of
the array. Returns 0 on success and -1 on error.

int json_array_insert_new( *array, size_t index,  *value)

Like but steals the reference to
value. This is useful when value is newly created and not used
after the call.

int json_array_remove( *array, size_t index)

Removes the element in array at position index, shifting the
elements after index one position towards the start of the array.
Returns 0 on success and -1 on error. The reference count of the
removed value is decremented.

int json_array_clear( *array)

Removes all elements from array. Returns 0 on sucess and -1 on
error. The reference count of all removed values are decremented.

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.

Добавить комментарий

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

Adblock
detector