산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python JSON:인코딩(덤프), 디코딩(로드) 및 JSON 파일 읽기

파이썬에서 JSON이란 무엇입니까?

JSON Python의 은(는) 네트워크를 통한 텍스트 형식으로 데이터 교환 및 데이터 전송을 위한 JavaScript에서 영감을 받은 표준 형식입니다. 일반적으로 JSON은 문자열 또는 텍스트 형식입니다. API 및 데이터베이스에서 사용할 수 있으며 개체를 이름/값 쌍으로 나타냅니다. JSON은 JavaScript Object Notation의 약자입니다.

Python JSON 구문:

JSON은 키와 값 쌍으로 작성됩니다.

{
        "Key":  "Value",
        "Key":  "Value",
} 

JSON은 과(와) 매우 유사합니다. 파이썬 사전. Python은 JSON을 지원하며 JSON으로 라이브러리가 내장되어 있습니다.

Python의 JSON 라이브러리

'마샬 ' 및 '피클' Python의 외부 모듈은 JSON 버전을 유지합니다. 파이썬 라이브러리. 인코딩 및 디코딩과 같은 JSON 관련 작업을 수행하기 위해 Python에서 JSON을 사용하려면 먼저 가져오기 가 필요합니다. JSON 라이브러리 및 이에 대한 .py 파일,

import json

JSON Python 모듈에서 사용할 수 있는 메서드는 다음과 같습니다.

메소드 설명
덤프() JSON 객체로 인코딩
덤프() 파일에 인코딩된 문자열 쓰기
로드() JSON 문자열 디코딩
로드() JSON 파일을 읽는 동안 디코딩

Python에서 JSON으로(인코딩)

Python의 JSON 라이브러리는 기본적으로 다음과 같은 Python 개체를 JSON 개체로 변환합니다.

파이썬 JSON
딕셔너리 개체
목록 배열
유니코드 문자열
숫자 – int, long 숫자 – 정수
플로트 숫자 – 실수
사실 사실
거짓 거짓
없음

Python 데이터를 JSON으로 변환하는 것을 인코딩 작업이라고 합니다. 인코딩은 JSON 라이브러리 메서드인 dumps()를 사용하여 수행됩니다.

Python의 JSON dumps()

json.dumps() Python에서 는 Python의 사전 개체를 JSON 문자열 데이터 형식으로 변환하는 메서드입니다. 구문 분석, 인쇄 등과 같은 작업을 위해 개체가 문자열 형식이어야 할 때 유용합니다.

이제 Python으로 첫 번째 json.dumps 인코딩 예제를 수행해 보겠습니다.

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice","Bob"),
  "pets": ['Dog'],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  ]
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

출력:

{"person": {"name": "Kenn", "sex": "male", "age": 28}})

동일한 함수 dump()를 사용하여 사전의 JSON 파일을 생성하기 위해 Python이 파일에 JSON을 작성하는 예를 살펴보겠습니다.

# here we create new data_file.json file with write mode using file i/o operation 
with open('json_file.json', "w") as file_write:
# write json data into file
json.dump(person_data, file_write)

출력:

표시할 항목이 없습니다... 시스템에 json_file.json이 생성됩니다. 아래의 write JSON to file Python 예제와 같이 해당 파일을 확인할 수 있습니다.

JSON에서 Python으로(디코딩)

JSON 문자열 디코딩은 내장 메소드 json.loads()를 사용하여 수행됩니다. &json.load() Python의 JSON 라이브러리. 다음 번역 테이블은 JSON 문자열의 Python에서 디코딩을 수행하는 데 도움이 되는 Python 개체에 대한 JSON 개체의 예를 보여줍니다.

JSON 파이썬
객체 딕셔너리
배열 목록
문자열 유니코드
숫자 – 정수 숫자 – 정수, 긴
숫자 – 실수 플로트
사실 사실
거짓 거짓
없음

json.loads를 사용하여 디코딩하는 기본 구문 분석 JSON Python 예제를 살펴보겠습니다. 기능,

import json  # json library imported
# json data string
person_data = '{  "person":  { "name":  "Kenn",  "sex":  "male",  "age":  28}}'
# Decoding or converting JSON format in dictionary using loads()
dict_obj = json.loads(person_data)
print(dict_obj)
# check type of dict_obj
print("Type of dict_obj", type(dict_obj))
# get human object details
print("Person......",  dict_obj.get('person'))

출력:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}
Type of dict_obj <class 'dict'>
Person...... {'name': 'John', 'sex': 'male'}

Python에서 JSON 파일 디코딩 또는 JSON 파일 구문 분석

이제 Python parse JSON 예제를 사용하여 Python에서 JSON 파일을 읽는 방법을 배웁니다.

참고: JSON 파일 디코딩은 File Input/Output(I/O) 관련 작업입니다. JSON 파일은 프로그램에서 언급한 지정된 위치의 시스템에 있어야 합니다.

Python 읽기 JSON 파일 예:

import json
#File I/O Open function for read data from JSON File
with open('X:/json_file.json') as file_object:
        # store file data in object
        data = json.load(file_object)
print(data)

여기 데이터 위의 읽기 JSON 파일 Python 예제와 같이 Python의 사전 객체입니다.

출력:

{'person': {'name': 'Kenn', 'sex': 'male', 'age': 28}}

Python의 압축 인코딩

JSON 파일의 크기를 줄여야 하는 경우 Python에서 압축 인코딩을 사용할 수 있습니다.

예,

import json
# Create a List that contains dictionary
lst = ['a', 'b', 'c',{'4': 5, '6': 7}]
# separator used for compact representation of JSON.
# Use of ',' to identify list items
# Use of ':' to identify key and value in dictionary
compact_obj = json.dumps(lst, separators=(',', ':'))
print(compact_obj)

출력:

'["a", "b", "c", {"4": 5, "6": 7}]'

** Here output of JSON is represented in a single line which is the most compact representation by removing the space character from compact_obj **

JSON 코드 형식 지정(예쁜 인쇄)

예:

import json
dic = { 'a': 4, 'b': 5 }
''' To format the code use of indent and 4 shows number of space and use of separator is not necessary but standard way to write code of particular function. '''
formatted_obj = json.dumps(dic, indent=4, separators=(',', ': '))
print(formatted_obj)

출력:

{
   "a" : 4,
   "b" : 5
}

이것을 더 잘 이해하려면 들여쓰기를 40으로 변경하고 출력을 관찰하십시오-

JSON 코드 주문:

정렬 키 Python 덤프 함수의 인수에 있는 속성은 JSON의 키를 오름차순으로 정렬합니다. sort_keys 인수는 부울 속성입니다. 정렬이 허용되면 그렇지 않으면 허용되지 않습니다. Python string to JSON 정렬 예제로 이해합시다.

예,

import json

x = {
  "name": "Ken",
  "age": 45,
  "married": True,
  "children": ("Alice", "Bob"),
  "pets": [ 'Dog' ],
  "cars": [
    {"model": "Audi A1", "mpg": 15.1},
    {"model": "Zeep Compass", "mpg": 18.1}
  	],
}
# sorting result in asscending order by keys:
sorted_string = json.dumps(x, indent=4, sort_keys=True)
print(sorted_string)

출력:

{
    "age": 45,
    "cars": [ {
        "model": "Audi A1", 
        "mpg": 15.1
    },
    {
        "model": "Zeep Compass", 
        "mpg": 18.1
    }
    ],
    "children": [ "Alice",
		  "Bob"
	],
    "married": true,
    "name": "Ken",
    "pets": [ 
		"Dog"
	]
}

키 나이를 보시면 알겠지만 자동차, 어린이 등이 오름차순으로 정렬되어 있습니다.

Python의 복잡한 객체 인코딩

복잡한 개체에는 다음과 같은 두 가지 부분이 있습니다.

  1. 실제 부분
  2. 허수부

예:3 +2i

복잡한 객체의 인코딩을 수행하기 전에 변수가 복잡한지 여부를 확인해야 합니다. 인스턴스 메소드를 사용하여 변수에 저장된 값을 확인하는 함수를 만들어야 합니다.

객체가 복잡하거나 인코딩에 적합한 검사를 위한 특정 함수를 만들어 보겠습니다.

import json

# create function to check instance is complex or not
def complex_encode(object):
    # check using isinstance method
    if isinstance(object, complex):
        return [object.real, object.imag]
    # raised error using exception handling if object is not complex
    raise TypeError(repr(object) + " is not JSON serialized")


# perform json encoding by passing parameter
complex_obj = json.dumps(4 + 5j, default=complex_encode)
print(complex_obj)

출력:

'[4.0, 5.0]'

Python의 복잡한 JSON 객체 디코딩

JSON에서 복잡한 객체를 디코딩하려면 JSON 문자열에 복잡한 객체가 포함되어 있는지 확인하는 object_hook 매개변수를 사용합니다. JSON Python 예제에 문자열로 이해하자,

import json
  # function check JSON string contains complex object
  def is_complex(objct):
    if '__complex__' in objct:
      return complex(objct['real'], objct['img'])
    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)

출력:

Complex_object...... (4+5j)
Without_complex_object...... {'real': 6, 'img': 7}

JSON 직렬화 클래스 JSONEncoder 개요

JSONEncoder 클래스는 인코딩을 수행하는 동안 모든 Python 개체의 직렬화에 사용됩니다. 여기에는 세 가지 다른 인코딩 방법이 포함되어 있습니다.

JSONEncoder 클래스의 encode() 메서드를 사용하여 아래 Python JSON 인코더 예제와 같이 모든 Python 객체를 인코딩할 수도 있습니다.

# import JSONEncoder class from json
from json.encoder import JSONEncoder
colour_dict = { "colour": ["red", "yellow", "green" ]}
# directly called encode method of JSON
JSONEncoder().encode(colour_dict)

출력:

'{"colour": ["red", "yellow", "green"]}'

JSON Deserialization 클래스 JSONDecoder 개요

JSONDecoder 클래스는 디코딩을 수행하는 동안 모든 Python 개체의 직렬화 해제에 사용됩니다. 여기에는 세 가지 디코딩 방법이 포함되어 있습니다.

JSONDecoder 클래스의 decode() 메서드를 사용하여 아래 Python JSON 디코더 예제와 같이 JSON 문자열을 디코딩할 수도 있습니다.

import json
# import JSONDecoder class from json
from json.decoder import JSONDecoder
colour_string = '{ "colour": ["red", "yellow"]}'
# directly called decode method of JSON
JSONDecoder().decode(colour_string)

출력:

{'colour': ['red', 'yellow']}

URL에서 JSON 데이터 디코딩:실제 예

지정된 URL(https://feeds.citibikenyc.com/stations/stations.json)에서 CityBike NYC(자전거 공유 시스템)의 데이터를 가져와 사전 형식으로 변환합니다.

Python 파일에서 JSON 로드 예:

참고:- Python에 요청 라이브러리가 이미 설치되어 있는지 확인하고 그렇지 않은 경우 터미널 또는 CMD를 열고

를 입력합니다.
import json
import requests

# get JSON string data from CityBike NYC using web requests library
json_response= requests.get("https://feeds.citibikenyc.com/stations/stations.json")
# check type of json_response object
print(type(json_response.text))
# load data in loads() function of json library
bike_dict = json.loads(json_response.text)
#check type of news_dict
print(type(bike_dict))
# now get stationBeanList key data from dict
print(bike_dict['stationBeanList'][0]) 

출력:

<class 'str'>
<class 'dict'>
{
	'id': 487,
 	'stationName': 'E 20 St & FDR Drive',
	'availableDocks': 24,
	'totalDocks': 34,
	'latitude': 40.73314259,
	'longitude': -73.97573881,
	'statusValue': 'In Service',
	'statusKey': 1,
	'availableBikes': 9,
	'stAddress1': 'E 20 St & FDR Drive',
	'stAddress2': '',
	'city': '',
	'postalCode': '',
	'location': '', 
	'altitude': '', 
	'testStation': False, 
	'lastCommunicationTime': '2018-12-11 10:59:09 PM', 'landMark': ''
}

Python의 JSON 라이브러리와 관련된 예외:

Python 파일에서 JSON 로드 예:

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의 무한 및 NaN 숫자

JSON 데이터 교환 형식(RFC – Request For Comments)은 Infinite 또는 Nan Value를 허용하지 않지만 Python-JSON 라이브러리에서 Infinite 및 Nan Value 관련 작업을 수행하는 데 제한이 없습니다. JSON이 INFINITE 및 Nan 데이터 유형을 가져오면 리터럴로 변환됩니다.

예,

import json
# pass float Infinite value
infinite_json = json.dumps(float('inf'))
# check infinite json type
print(infinite_json)
print(type(infinite_json))
json_nan = json.dumps(float('nan'))
print(json_nan)
# pass json_string as Infinity
infinite = json.loads('Infinity')
print(infinite)
# check type of Infinity
print(type(infinite))

출력:

Infinity
<class 'str'>
NaN
inf
<class 'float'>	

JSON 문자열의 반복된 키

RFC는 키 이름이 JSON 개체에서 고유해야 한다고 지정하지만 필수는 아닙니다. Python JSON 라이브러리는 JSON에서 반복되는 객체의 예외를 발생시키지 않습니다. 반복되는 모든 키-값 쌍을 무시하고 그 중 마지막 키-값 쌍만 고려합니다.

import json
repeat_pair = '{"a":  1, "a":  2, "a":  3}'
json.loads(repeat_pair)

출력:

{'a': 3}

Python에서 JSON을 사용하는 CLI(명령줄 인터페이스)

json.tool JSON pretty-print 구문의 유효성을 검사하는 명령줄 인터페이스를 제공합니다. CLI의 예를 살펴보겠습니다.

$ echo '{"name" : "Kings Authur" }' | python3 -m json.tool

출력:

{
    "name": " Kings Authur "
}

Python에서 JSON의 장점

Python에서 JSON의 구현 제한 사항

파이썬 JSON 치트 시트

파이썬 JSON 함수 설명
json.dumps(person_data) JSON 객체 생성
json.dump(person_data, file_write) Python의 File I/O를 이용한 JSON 파일 생성
compact_obj =json.dumps(데이터, 구분 기호=(',',':')) 구분 기호를 사용하여 JSON 개체에서 공백 문자를 제거하여 JSON 개체 압축
formatted_obj =json.dumps(dic, indent=4, separators=(',', ':')) 들여쓰기를 사용하여 JSON 코드 형식 지정
sorted_string =json.dumps(x, 들여쓰기=4, sort_keys=True) 알파벳 순서로 JSON 객체 키 정렬
complex_obj =json.dumps(4 + 5j, 기본값=complex_encode) JSON의 Python 복합 객체 인코딩
JSONEncoder().encode(color_dict) 직렬화를 위한 JSONEncoder 클래스 사용
json.loads(data_string) json.loads() 함수를 사용하여 Python 사전에서 JSON 문자열 디코딩
json.loads('{"__complex__":true, "실제":4, "img":5}', object_hook =is_complex) 복잡한 JSON 객체를 Python으로 디코딩
JSONDecoder().decode(color_string) 역직렬화를 통해 JSON을 Python으로 디코딩 사용

python

  1. 파이썬 데이터 유형
  2. 파이썬 연산자
  3. 파이썬 while 루프
  4. 파이썬 통과 문
  5. 파이썬 함수 인수
  6. 파이썬 사전
  7. 파이썬 파일 I/O
  8. Java BufferedReader:예제를 사용하여 Java에서 파일을 읽는 방법
  9. Python 파일 존재 여부 확인 | 파이썬에서 디렉토리가 존재하는지 확인하는 방법
  10. 파이썬 - 파일 I/O