반응형
사전을 JSON으로 변환하는 중
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))
JSON에서 데이터에 액세스할 수 없습니다.내가 뭘 잘못하고 있지?
TypeError: string indices must be integers, not str
json.dumps()
사전을 로 변환하다str
오브젝트, a가 아닌json(dict)
오브젝트!그래서 당신은 로딩해야 합니다.str
에dict
방법을 써서 쓰다
봐json.dumps()
저장 방법으로서json.loads()
검색 메서드로 사용합니다.
다음은 코드 샘플로 이해를 도울 수 있습니다.
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
json.dumps()
python dict의 JSON 문자열 표현을 반환합니다.문서를 참조해 주세요.
할 수 없다r['rating']
r은 문자열이고 더 이상 dict가 아니기 때문에
아마도 당신은 다음과 같은 것을 의미했을 것이다.
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))
json.dumps()
JSON 데이터를 디코딩하는 데 사용됩니다.
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
출력:
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 개체에서 JSON으로 데이터 변환
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
갱신하다
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)
차트 응답
로 출력하다.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
인스턴스에서 JSON으로
- 심플한 솔루션:
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
- 한층 더 심플하게
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())
차트 응답
출력:
{
"web": "Stackoverflow",
"type": "Knowledge",
"is_the_best": true,
"user": {
"name": "Milovan",
"age": 34
}
}
를 사용하여 문자열로 변환할 필요가 없습니다.json.dumps()
r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))
값은 dict 객체에서 직접 얻을 수 있습니다.
r을 사전으로 정의하면 다음과 같은 효과를 얻을 수 있습니다.
>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>
위의 예에서 기본 사전 내에 새 사전을 선언하여 중첩된 사전을 만들 수 있습니다.
import json
dictionary = {
'fruit':{"Grapes": "10","color": "green"},
'vegetable':{"chilli": "4","color": "red"},
}
result = json.dumps(dictionary, indent = 3)
인쇄(결과)
여기에서는 ind=3을 사용했습니다.
참고 자료: https://favtutor.com/blogs/dict-to-json-python
언급URL : https://stackoverflow.com/questions/26745519/converting-dictionary-to-json
반응형
'programing' 카테고리의 다른 글
MySQL의 로드 데이터 파일에 대한 액세스가 거부되었습니다. (0) | 2022.10.08 |
---|---|
yield()의 주요 용도는 무엇이며 join() 및 interrupt()와는 어떻게 다릅니까? (0) | 2022.10.08 |
MariaDB에서 생성된 열 정의의 사용자 정의 함수? (0) | 2022.10.08 |
인쇄용 if 스테이트먼트를 인라인으로 쓰는 방법 (0) | 2022.10.08 |
Python에서 현재 OS를 찾으려면 어떻게 해야 하나요? (0) | 2022.10.08 |