파이썬 | json 파일 읽기

파이썬은 json 파일을 읽습니다.

json 파일

  JSON (JavaScript Object Notation)은 가벼운 데이터 교환 형식입니다. 텍스트 파일로 사용할 수 있습니다. 비교를 위해 json 파일을 읽는 두 가지 방법이 있습니다. json 파일을 읽는 두 가지 주요 방법은 약간 다른 후속 코드로 이어집니다.

Predict1_-mixer.json :

{
    
    
  "projection": {
    
    
    "crs": "EPSG:4326",
    "affine": {
    
    
      "doubleMatrix": [8.983152841195215E-4, 0.0, 13.599595086285436, 0.0, -8.983152841195215E-4, 45.40175277468474]
    }
  },
  "patchDimensions": [256, 256],
  "patchesPerRow": 5,
  "totalPatches": 10
}
{
    
    'projection': {
    
    'crs': 'EPSG:4326', 'affine': {
    
    'doubleMatrix': [0.0008983152841195215, 0.0, 13.599595086285436, 0.0, -0.0008983152841195215, 45.40175277468474]}}, 'patchDimensions': [256, 256], 'patchesPerRow': 5, 'totalPatches': 10}

!고양이

import json
jsonFile='Predict1_-mixer.json'

jsonText = !cat {
    
    jsonFile}
mixer = json.loads(jsonText.nlstr)

patches = mixer['totalPatches']
patchesPerRow = mixer['patchesPerRow']

이 메소드의 jsonText는 추가 처리가 필요합니다.

['{',
 '  "projection": {',
 '    "crs": "EPSG:4326",',
 '    "affine": {',
 '      "doubleMatrix": [8.983152841195215E-4, 0.0, 13.599595086285436, 0.0, -8.983152841195215E-4, 45.40175277468474]',
 '    }',
 '  },',
 '  "patchDimensions": [256, 256],',
 '  "patchesPerRow": 5,',
 '  "totalPatches": 10',
 '}']

믹서 출력은 다음과 같습니다.

{
    
    'patchDimensions': [256, 256],
 'patchesPerRow': 5,
 'projection': {
    
    'affine': {
    
    'doubleMatrix': [0.0008983152841195215,
    0.0,
    13.599595086285436,
    0.0,
    -0.0008983152841195215,
    45.40175277468474]},
  'crs': 'EPSG:4326'},
 'totalPatches': 10}

열다()

import json
jsonFile='Predict1_-mixer.json'

with open(jsonFile, 'r') as myfile:
  jsonText=myfile.read()
mixer = json.loads(jsonText)

patches = mixer['totalPatches']
patchesPerRow = mixer['patchesPerRow']

jsonFile 메소드는 추가 처리가 필요하지 않으며 직접 loads()다음 과 같이 할 수 있습니다 .

{
    
    
  "projection": {
    
    
    "crs": "EPSG:4326",
    "affine": {
    
    
      "doubleMatrix": [8.983152841195215E-4, 0.0, 13.599595086285436, 0.0, -8.983152841195215E-4, 45.40175277468474]
    }
  },
  "patchDimensions": [256, 256],
  "patchesPerRow": 5,
  "totalPatches": 10
}

믹서 출력은 일관됩니다.

{
    
    'patchDimensions': [256, 256],
 'patchesPerRow': 5,
 'projection': {
    
    'affine': {
    
    'doubleMatrix': [0.0008983152841195215,
    0.0,
    13.599595086285436,
    0.0,
    -0.0008983152841195215,
    45.40175277468474]},
  'crs': 'EPSG:4326'},
 'totalPatches': 10}

추천

출처blog.csdn.net/weixin_43360896/article/details/111322643