python | read json file

python read json file

json file

  JSON (JavaScript Object Notation) is a lightweight data exchange format. Can be used as a text file. Here are two ways to read json files, for comparison. The main two methods of reading json files lead to slightly different subsequent codes.

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}

!cat

import json
jsonFile='Predict1_-mixer.json'

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

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

The jsonText of this method needs further processing:

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

The mixer output is as follows:

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

open()

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

The method jsonFile does not require further processing , and can be directly 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
}

The mixer output is consistent:

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

Guess you like

Origin blog.csdn.net/weixin_43360896/article/details/111322643