Reading from python objects
"""
When you want to read from python string object and conver to python Dict:
json.loads(pythonString) --> result is python dict
when you want to write to
"""
import json
string = '{"id":"09", "name": "Nitin", "department":"Finance"}'
# This will convert json string into json dictionary in python
jdict = json.loads(jobject)
print(jdict)
{'id': '09', 'name': 'Nitin', 'department': 'Finance'}
# Converting a json dict into python string object
jstring = json.dumps(jdict)
print(jstring)
#ouput:
"{'id': '09', 'name': 'Nitin', 'department': 'Finance'}"
Opening and reading JSON from file
"""
When you are reading from file:
use json.load()
When you want to write to a file:
use json.dump()
"""
import json
with open('data.json', r) as f:
data = json.load(f)
print(data)
# Python Dictonary
{'fruit': 'Apple', 'size': 'Large', 'color': 'Red'}
# Use this dictionary to write back into file
with open('newfile.json', 'w') as f:
json.dump(data, f)
# that should create a new file in cwd with name of newfile.json
#!/bin/python3
# string.capitalize for making the first letter in Upper case
a_string = input().split(' ')
result = ' '.join((word.capitalize() for word in a_string))
print(result)
# this will give list of index on which the substring is appearing
string = "hello"
indexList= [n for n in range(len(string)) if string.find('ll', n) == n]
Output:
[2, 3]
string = "BANANA"
# here i represents index of letter in the string and letter represents letter
list1 = [letter for i, letter in enumerate(string)]
# If you want to find occurences of a letter in this string then:
t = "A"
list2 = [letter for i, letter in enumerate(string) if letter == t]