# 39 이 JSON 데이터를 분석할 can& t 파이썬, 왜?

나는 이 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)

이 프로그램은 표시되어도 예외를 던진다.

<! - 언어: &gt 랑 없음 -;

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] (https://www.json.org/) 형식입니다. 당신은 ' []' 할 때 ' {}':

  • ' []' 라고 하는 '목록' 의 파이썬 JSON 어레이에는 위한 것입니다. {} '-' 라고 하는 '' 의 파이썬 딕트 JSON 객체에는 위한 것입니다.

39 의 파일 JSON here& 방법을 고려해야 합니다.

{
    "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"]

쉽게 이해할 수 있는지 그 시도하시겠습니까 로그아웃되며 시작됩니다.

해설 (14)

'네' 다타.j슨 다음과 같습니다.

{
 "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)

참고로 이 파이썬 2.6, 위로, 있는 그대로 따라 다릅니다 때만 ['을 (를)' 기술서임을] (http://docs.python.org/2/reference/compound_stmts.html # with 기술서임을). 파이썬 2.5 에서 사용할 수 있는 ',' 의 파이썬 2.4, 지켜보리니 with_statement future 가져오기의 < = [저스틴 Peel& # 39 의 오토메이티드] (https://stackoverflow.com/a/2835672/906658) 를 바탕으로 이 대답.

또한 다음과 같은 값을 단일 액세스 할 수 있습니다.

data["maps"][0]["id"]  # will return 'blabla'
data["masks"]["id"]    # will return 'valore'
data["om_points"]      # will return 'value'
해설 (7)

[# 39 의 저스틴 Peel& 오토메이티드] (https://stackoverflow.com/a/2835672/906658) 는 정말 도움됐네 있지만, 파이썬 사용할 경우 다음과 같은 3 판독값 JSON 봐야 한다.

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

참고: '대신' 사용 '제손드로이즈 제손드로이드'. Python 에서, '3' 는 제손드로이즈 문자열으로 매개변수입니다. '제손드로이드' 는 파일 류 객체에는 매개변수입니다. ' ()' 되돌려줍니다 data_file.read 문자열으로 객체에는.

솔직히 난 don& # 39, json 데이터 메모리로 로드하기에 it& # 39 의 모든 문제가 없는 것 같습니다, 대부분의 경우.

해설 (10)
data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
    for line in f:
       data.append(json.loads(line))
해설 (5)

울트라 JSON&quot "; 또는 단순히 &quot ujson"; 이 파일을 다룰 수 있는 ' []' 에 JSON 입력입니다. # 39 는 JSON you& 경우, re 판독값 프로그램에 입력 파일 압축을 목록으로 JSON 요소. 같은 ' [[{}], [], {}, {} 상술합니다.]' 의 임의의 순서를 사전, 사전을 열거합니다 우이슨 처리할 수 있습니다.

우이슨 [파이썬 패키지 인덱스] 에서 찾을 수 있습니다 (https://pypi.python.org/pypi/ujson) 및 API 는 json 라이브러리를 Python& # 39 에 내장된 ',' 거의 같습니다.

39 도 훨씬 더 빨리, 더 큰 경우 우이슨 you& re 로드중 JSON 파일. 반면 다른 파이썬 JSON 라이브러리를 동일한 성능을 확인할 수 있습니다 자세한 내용은 링크를.

해설 (0)

39 you& Python3 변경하는 경우, re ('코너스션.j슨' file) JSON 을 사용하여 볼 수 있습니다.

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

그럼 다음 코드를 사용하여:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1
해설 (2)

여기 다타.j슨 수정되었음 '와' file:

{
    "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)

"에 대한 걱정했던것 출력입니다 보기인쇄 (data_item [& # 39, parameters& # 39,] [0] [# 39, & # 39, id&]) '.

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

"에 대한 걱정했던것 출력입니다 보기인쇄 (data_item [& # 39, parameters& # 39,] [0] [# 39, & # 39, id&]) '.

valore
해설 (1)

이 두 가지 유형이 구문 분석.

  1. 구문 분석 데이터를 파일 시스템에서 경로
  2. 구문 분석 JSON 에서 원격 uirl.

파일에서 사용할 수 있습니다 다음

import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']

이 두 가지 방법으로 값을 가져오는 아스트리클레 전체 과정을 설명하는 구문 분석 및 시나리오에서와. [JSON 파이썬 사용하여 구문 분석] [1]

[1]: https://scriptcrunch.com/parse-json-file-using-python/ &quot 사용하여 구문 분석, JSON Python&quot.

해설 (0)

, 비호환성의 python3 사용자

중요한 차이점은 '로드' 는 json 데이터를 읽을 때 특히 '와' 로드되는지 메서드을 파일로부터는.

Docs 이다.

  • json.load:* &gt. Fp (그리드 () 는 텍스트 파일 또는 이진 지원하고 있습니다. 데즈리얼리즈 &gt. 파이썬 객체를 JSON 문서에 포함된 파일) 를 사용하여 이 &gt. 변환 테이블.

  • json.loads:*

&gt. 제손드로이즈: S (a str, 바이트입니다 또는 bytearray 인스턴스입니다 데즈리얼리즈 &gt. 파이썬 객체를 JSON 문서에 포함된) 를 사용하여 이 변환 &gt. 표.

json 문서를 읽을 수 있기 때문에 이진 파일을 직접 읽을 수 있는 방법을 제손드로이드 열었다.

with open('./recipes.json') as data:
  all_recipes = json.load(data)

따라서, json 데이터를 사용할 수 있는 형식으로 table:) 로 지정된 이 자료에 따르면 변환

https://docs.python.org/3.7/library/json.html # json 을 py 테이블

해설 (1)