\how to read a json file code example
Example 1: python read json file
import json
with open('path_to_file/person.json') as f:
data = json.load(f)
print(data)
Example 2: json dump to file
import json
data = {"key": "value"}
with open('data.json', 'w') as jsonfile:
json.dump(data, jsonfile)
Example 3: write json pythonb
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)
Example 4: write json pythonb
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('')
Example 5: how to create json file in python
#import the json module
import json
#create a dictionary which we can add to a json file
dictionary ={
"name" : "sathiyajith",
"rollno" : 56,
"cgpa" : 8.6,
"phonenumber" : "9976770500"
}
#open an object with following inputs: 'name_of_file.json', 'w'
#dump the content fromt he dictionary into the outfile
with open("sample.json", "w") as outfile:
json.dump(dictionary, outfile)
Example 6: read json data from file
// consider your file data is something like json string but aving parse issue
//that means some additional char is there
fs.readFile(ROLES_FILE, "utf8", (err, data) => {
if (err) {
res.status(403).json({});
}
const [localScope, action] = scope.split(".");
const mapper = JSON.parse(data.toString("utf8").replace(/^\uFEFF/, ""));
const isAllowed = checkRole(mapper, localScope, action, role);
if (isAllowed) {
next();
} else {
res.status(403).json({});
}