3

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

2
  • There is no such open mode as 't'. You either want 'w' to write, or 'r' to read the file. Also, the function you want is json.dump, not jsondump. Why are you sleeping for 5 seconds? That will irritate your users. Commented May 5, 2022 at 5:36
  • @TimRoberts Mode 't' does exist. It's even the default. Did you maybe look at the documentation for Python 2? Commented May 7, 2022 at 12:05

2 Answers 2

1
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))
Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

He TRIED to dump the data. Tell him how to fix it. That's what an answer does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.