0

I have little script on python and I want receive results into JSON file.

I prepared already JSON keys with names of tests.

It looks like this one:

{
    "key1" : ""
    "key2" : ""
    "key3" : ""

}

And now I want to save results (usual str (after if else tests)) as value into specified key.

How can I perform it?

Thank you!

EDIT: not create dictionary, not take FROM JSON. Only write to specified key.

Like (by script, of course):

"Write 'my_str' to My_json[My_key]"

4
  • Is the JSON you pasted in your question being read into the python program, or is it a dictionary that you want to convert to JSON? Commented Jun 21, 2020 at 15:17
  • We would need to see your values and how you get them to be able to help you insert them into json Commented Jun 21, 2020 at 15:18
  • Being read (using load) Commented Jun 21, 2020 at 15:19
  • Usual str 'Test "my_tests" passed/failed'' Commented Jun 21, 2020 at 15:20

2 Answers 2

1

to save dictionary into a json format you should use json lib which allows you to dump a dictionary in a json file and convert convert a .json into a python dictionary

import json

my_dict = {'key1':'', 'key2':'', 'key3':''}

def dump_data(data):
    with open('file.json', 'w') as file:
        json.dump(data, file)

def read_data(file_name):
    with open(file_name, 'r') as file:
        return json.load(file)

dump_data(my_dict)
my_dict2 = read_data('file.json')
Sign up to request clarification or add additional context in comments.

3 Comments

Keys already exist. I want to add values to existed keys.
my_dict = read_data('file.json') for key, value in zip(my_dict.keys(), your_values): my_dict[key] = value dump_data(my_dict)
Read - to take data FROM JSON, I want to add data TO JSON
1

You can import json, create a dictionary, and use:

    json_var = json.dumps(dict_var)

To transform it in json. See Python JSON.

Comments

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.