python | lire le fichier json

python lit le fichier json

fichier json

  JSON (JavaScript Object Notation) est un format d'échange de données léger. Peut être utilisé comme fichier texte. Voici deux façons de lire les fichiers json, à titre de comparaison. Les deux principales méthodes de lecture des fichiers json conduisent à des codes ultérieurs légèrement différents.

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}

!chat

import json
jsonFile='Predict1_-mixer.json'

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

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

Le jsonText de cette méthode nécessite un traitement supplémentaire:

['{',
 '  "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',
 '}']

La sortie du mélangeur est la suivante:

{
    
    '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}

ouvert()

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']

La méthode jsonFile ne nécessite pas de traitement supplémentaire et peut être directement 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
}

La sortie du mélangeur est cohérente:

{
    
    '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}

Je suppose que tu aimes

Origine blog.csdn.net/weixin_43360896/article/details/111322643
conseillé
Classement