it-source

Python이 이 JSON 데이터를 해석할 수 없는 이유는 무엇입니까?

criticalcode 2022. 11. 29. 21:46
반응형

Python이 이 JSON 데이터를 해석할 수 없는 이유는 무엇입니까?

파일에는 다음 JSON이 있습니다.

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [
        "id": "valore"
    ],
    "om_points": "value",
    "parameters": [
        "id": "valore"
    ]
}

모든 JSON 데이터를 인쇄하기 위해 이 스크립트를 작성했습니다.

import json
from pprint import pprint

with open('data.json') as f:
    data = json.load(f)

pprint(data)

단, 이 프로그램에서는 예외가 발생합니다.

Traceback (most recent call last):
  File "<pyshell#1>", line 5, in <module>
    data = json.load(f)
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 13 column 13 (char 213)

JSON을 해석하고 값을 추출하려면 어떻게 해야 합니까?

데이터가 올바른 JSON 형식이 아닙니다.당신은 가지고 있다[]해야 할 때{}를 위해"masks"그리고."parameters"요소:

  • []JSON 어레이용입니다.listPython에서
  • {}JSON 오브젝트용입니다.dictPython에서

JSON 파일의 모양은 다음과 같습니다.

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": {
        "id": "valore"
    },
    "om_points": "value",
    "parameters": {
        "id": "valore"
    }
}

그런 다음 코드를 사용할 수 있습니다.

import json
from pprint import pprint

with open('data.json') as f:
    data = json.load(f)

pprint(data)

데이터를 사용하여 다음과 같은 값도 찾을 수 있습니다.

data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]

시험해보고 말이 되는지 봐.

당신의.data.json는 다음과 같습니다.

{
 "maps":[
         {"id":"blabla","iscategorical":"0"},
         {"id":"blabla","iscategorical":"0"}
        ],
"masks":
         {"id":"valore"},
"om_points":"value",
"parameters":
         {"id":"valore"}
}

코드는 다음과 같습니다.

import json
from pprint import pprint

with open('data.json') as data_file:    
    data = json.load(data_file)
pprint(data)

이것은 - 스테이트먼트에 따라 다르기 때문에 Python 2.6 이상에서만 동작합니다.Python 2.5에서 사용from __future__ import with_statementPython <= 2.4에서 이 답변의 기반이 되는 Justin Peel의 답변을 참조하십시오.

다음과 같은 단일 값에 액세스할 수도 있습니다.

data["maps"][0]["id"]  # will return 'blabla'
data["masks"]["id"]    # will return 'valore'
data["om_points"]      # will return 'value'

여기 수정 완료data.json파일:

{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": [{
        "id": "valore"
    }],
    "om_points": "value",
    "parameters": [{
        "id": "valore"
    }]
}

다음 행을 사용하여 콘솔에서 데이터를 호출하거나 인쇄할 수 있습니다.

import json
from pprint import pprint
with open('data.json') as data_file:
    data_item = json.load(data_file)
pprint(data_item)

예상되는 출력print(data_item['parameters'][0]['id']):

{'maps': [{'id': 'blabla', 'iscategorical': '0'},
          {'id': 'blabla', 'iscategorical': '0'}],
 'masks': [{'id': 'valore'}],
 'om_points': 'value',
 'parameters': [{'id': 'valore'}]}

예상되는 출력print(data_item['parameters'][0]['id']):

valore

언급URL : https://stackoverflow.com/questions/2835559/why-cant-python-parse-this-json-data

반응형