python list to json code example

Example 1: python json string to object

import json

x =  '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)

print(y["age"])

Example 2: list to json python

import json
friends_list = [
    'John','Rambo','Sam',
]
json_format = json.dumps(friends_list)
print(json_format)
print(type(json_format))
#PYTHON OUTPUT
["John", "Rambo", "Sam"]
<class 'str'>

Example 3: python list

#Creating lists
my_list = [1, "Hello", 3.4, 0, "World"]
my_nested_list = [['Hello', 'World'],[47,39]]

#Accessing lists
my_list[1] # Hello
my_list[-2] # 0
my_list[:3] # [1, "Hello", 3.4]
my_nested_list[1] #[47,39]
my_nested_list[0][1] # World

Example 4: write list of dictionaries to json python

def filewriter(line):
    dictionary = {}
    dictionary['name'] = line[0][0] #assume this is a a string
    dictionary['item_to_buy'] = line[0][1]
    dictionary['currency'] = line[0][2]
    dictionary['league'] = line[0][3]
    with open('logs.json', 'r+') as f:
        if len(f.read()) == 0:
            f.write(json.dumps(dictionary))
        else:
            f.write(',\n' + json.dumps(dictionary))

def retrieve():
    with open('logs.json') as f:
        g = json.load(f)
        print(g[1]['name'])

Tags:

Cpp Example