티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Converting dictionary to JSON
딕셔너리를 JSON으로 변환하기
문제 내용
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))
I am not able to access my data in the JSON. What am I doing wrong?
저는 제 데이터를 JSON에서 접근할 수 없습니다. 무엇이 잘못된 것일까요?
TypeError: string indices must be integers, not str
높은 점수를 받은 Solution
json.dumps()
converts a dictionary to str
object, not a json(dict)
object! So you have to load your str
into a dict
to use it by using json.loads()
method
json.dumps() 함수는 딕셔너리를 str 객체로 변환하는 함수입니다. 즉, json(dict) 객체가 아닌 것입니다. 그러므로 json.loads() 메소드를 사용하여 str을 dict로 변환해야 합니다.
See json.dumps()
as a save method and json.loads()
as a retrieve method.
json.dumps()는 저장하는 메소드, json.loads()는 검색하는 메소드로 생각하시면 됩니다.
This is the code sample which might help you understand it more:
아래는 이해를 돕기 위한 코드 샘플입니다.
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
가장 최근 달린 Solution
json.dumps()
is used to decode JSON data
json.dumps() 함수는 JSON 데이터를 디코드하는 데 사용됩니다.
json.loads
take a string as input and returns a dictionary as output.json.dumps
take a dictionary as input and returns a string as output.
json.loads() 함수는 문자열을 입력으로 받아 딕셔너리를 출력합니다.
json.dumps() 함수는 딕셔너리를 입력으로 받아 문자열을 출력합니다.
import json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
출력:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
- Python Object to JSON Data Conversion
파이썬 객체를 JSON 데이터로 변환하는 방법
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
UPDATE
업데이트
In the JSON file
JSON 파일에서
nested_dictionary = {
'one': nested_list,
'two': dictionary,
}
json_dict = {'Nested Dictionary': nested_dictionary,
'Multiple':[nested_dictionary, nested_dictionary, nested_dictionary]
}
with open("test_nested.json", "w") as outfile:
json.dump(json_dict, outfile, indent=4, sort_keys=False)
chart response
차트 응답
output into test_nested.json
test_nested.json으로 출력하세요.
{
"Nested Dictionary": {
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
},
"Multiple": [
{
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
},
{
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
},
{
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
}
]
}
class
instance to JSON
클래스 인스턴스를 JSON으로
- A simple solution:
간단한 해결책:
class Foo(object):
def __init__(
self,
data_str,
data_int,
data_float,
data_list,
data_n_list,
data_dict,
data_n_dict):
self.str_data = data_str
self.int_data = data_int
self.float_data = data_float
self.list_data = data_list
self.nested_list = data_n_list
self.dictionary = data_dict
self.nested_dictionary = data_n_dict
foo = Foo(
str_data,
int_data,
float_data,
list_data,
nested_list,
dictionary,
nested_dictionary)
# Because the JSON object is a Python dictionary.
result = json.dumps(foo.__dict__, indent=4)
# See table above.
# or with built-in function that accesses .__dict__ for you, called vars()
# result = json.dumps(vars(foo), indent=4)
print(result) # same as before
- Even simpler
더욱 간단한 방법:
class Bar:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=False, indent=4)
bar = Bar()
bar.web = "Stackoverflow"
bar.type = "Knowledge"
bar.is_the_best = True
bar.user = Bar()
bar.user.name = "Milovan"
bar.user.age = 34
print(bar.toJSON())
chart response
차트 응답
output:
출력:
{
"web": "Stackoverflow",
"type": "Knowledge",
"is_the_best": true,
"user": {
"name": "Milovan",
"age": 34
}
}
출처 : https://stackoverflow.com/questions/26745519/converting-dictionary-to-json
'개발 > 파이썬' 카테고리의 다른 글
리스트를 청크(chunk) 단위로 반복하는 방법 (0) | 2023.01.24 |
---|---|
파일 열 때 't' 옵션의 용도 (0) | 2023.01.21 |
문자열 리스트를 쉼표로 구분된 문자열로 만들기 (0) | 2023.01.19 |
딕셔너리에 딕셔너리 추가하기 (0) | 2023.01.19 |
순환 참조시 하위 호출 스택에서만 ImportError가 발생하는 이유 (0) | 2023.01.18 |