Wednesday, 10 May 2017

how to working with JSON files in python





  • JSON (JavaScript Object Notation) is a lightweight data-interchange format. 
  • It is easy for humans to read and write. 
  • It is easy for machines to parse and generate. 
  • It is based on a subset of the JavaScript Programming Language.
  • in-order to work with JSON file, we are importing the json module.
json file example:


{"name": "Frank", "age": 39, "isEmployed": true}



Reading JSON:

  • Reading JSON means converting JSON into a Python value (object)
  • the json library parses JSON into a dictionary or list in Python. 
  • In order to do that, we use the loads( ) function (load from a string).


import json

jsonData = '{"name": "Frank", "age": 39}'

jsonToPython = json.loads(jsonData)

print(jsonToPython)

{ 'age' : 39, 'name' : 'Frank' }


writing json:

import json

pythonDictionary ={'name':'Bob','age':44,'isEmployed':True}

dictionaryToJson = json.dumps(pythonDictionary)

print(dictionaryToJson)


{ "age": 44, "isEmployed": true, "name": "Bob" }


config/defaults.json

{

"region" : "eu-west-1", "instanceType": "m1.small"

}

import json

config = json.loads(open('config/defaults.json').read( ))

print(config)

Writing the json file data into text file:
--------------------------------------------------
import json

data = {}  
data['people'] = []  
data['people'].append({  
    'name': 'Scott',
    'website': 'stackabuse.com',
    'from': 'Nebraska'
})
data['people'].append({  
    'name': 'Larry',
    'website': 'google.com',
    'from': 'Michigan'
})
data['people'].append({  
    'name': 'Tim',
    'website': 'apple.com',
    'from': 'Alabama'
})

with open('data.txt', 'w') as outfile:  

    json.dump(data, outfile)

Reading the data from text file to json:
---------------------------------------------------

import json

with open('data.txt') as json_file:  
    data = json.load(json_file)
    for p in data['people']:
        print('Name: ' + p['name'])
        print('Website: ' + p['website'])
        print('From: ' + p['from'])
        print('')



No comments:

Post a Comment