Home > Back-end >  How to dump data into Json file using python
How to dump data into Json file using python

Time:05-05

How to dump data into Json file *as can see in the below python code I am trying the dump data in Json file so but I am struggling to do it in python code *

import time
import json
import os


def long_function(name):
    cache_path = 'cache.json'
    if not os.path.isfile(cache_path):
        with open(cache_path, 't') as json_file:
            cache_file_data = [name]
            jsondump(cache_file_data, json_file)
    else:
        with open(cache_path, 'r') as json_file:
            cache_file_data = json.load(json_file)

    if name in cache_file_data:
        print("Name already exist")
        return name
    else:
        cache_file_data.append(name)
        for e in range(5):
            time.sleep(1)
            print(e 1)
        with open(cache_path, 'w') as json_file:
            jsondump(cache_file_data, json_file)
            print("New Name added in cache")
            return name


print(long_function('nitu'))

so please resolve my problem......please help me

CodePudding user response:

This is nothing but follow this pattern and your so your code error is ..you are not defined file mode correctly in if condition

with open (cache_path. "t") as json_file:

Instead of

with open (cache_path. "w") as json_file:

And second thing is you are not doing dump data

CodePudding user response:

import json
  
# JSON data:
x =  '{ "organization":"New_holn",
        "city":"Noida",
        "country":"India"}'
 
# python object to be appended
y = {"pin":117845}
 
# parsing JSON string:
z = json.loads(x)
  
# appending the data
z.update(y)
 
# the result is a JSON string:
print(json.dumps(z))
  • Related