What is the process for adding a value to a list in a JSON file?

How can I ensure that values are appended to a list in a JSON file without being overwritten every time the server is re-run?

{ "heart_rate": [ 72.18 ], "Experiment_time": [ 01/22/2023 11:59:59 ] }

I need new values to be added to the JSON file, so that each time a new value is obtained, it gets appended to the heartrate and Experiment_time lists under their corresponding keys, following the format shown below.

{ "heart_rate": [ 72.18,73.44 ], "Experiment_time": [ 01/22/2023 11:59:59,01/22/2023 11:60:00 ] }

My approach involves checking if the JSON file already exists, and creating one if it doesn't.

try:
    with open('Accounts.json','r') as fp:
        data = json.load(fp)
        f = data
        print(f)
        heartrate,dt_string = perform_all()

        lst1 = []

        if f != '':
            print("something")
        else:
            lst1.append(heartrate)
            
except :
    print("File Not found. Creating One")
    
    data = {}
    data['heart_rate'] = [None]
    data['Experiment_time'] = [None]
    
    
with open('Accounts.json','w') as fp:
    json.dump(data,fp,indent = 4)
heartrate,dt_string = perform_all() 

The function above returns one value of heart rate and one value of date-time when called.

Answer №1

Almost there, just remember to append to the correct dictionary key. Keep in mind that JSON encoding should be in UTF-8 as not all operating systems default to that encoding. This is particularly important if you are working with non-ASCII characters. Also, avoid using a bare except, specify the exception you anticipate instead.

import json
import datetime as dt

def perform_all():
    return 85, dt.datetime.now().strftime('%m/%d/%y %H:%M:%S')

try:
    with open('Accounts.json', encoding='utf8') as fp:
        data = json.load(fp)
        heartrate, dt_string = perform_all()
        data['heart_rate'].append(heartrate)
        data['Experiment_time'].append(dt_string)
except FileNotFoundError:
    print('File not found. Creating initial data...')
    data = {'heart_rate': [], 'Experiment_time': []}
       
with open('Accounts.json', 'w', encoding='utf8') as fp:
    json.dump(data, fp, indent=2)

Output:

C:\>test
File not found. Creating one...

C:\>test

C:\>test

C:\>type Accounts.json
{
  "heart_rate": [
    85,
    85
  ],
  "Experiment_time": [
    "01/26/23 21:34:22",
    "01/26/23 21:34:23"
  ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm currently attempting to utilize PTVS within Visual Studio, but am encountering difficulties in configuring the Python interpreter

I'm having trouble configuring the Python Tools for Visual Studio (PTVS) extension in my Visual Studio IDE. I have Visual Studio Enterprise 2015 installed along with Python 3.5.2, but I can't seem to set the Python interpreter correctly. When I ...

Error encountered while trying to utilize the modal input box in the Robot Framework Python script

I developed a Robot Framework code to interact with an input box inside a Modal that opens when a button is clicked. However, upon opening the modal, it displays a message stating that the "input box" is not interactable. It's worth noting that there ...

Decreasing window size near boundary for smoothing functions with fixed endpoints

I'm in search of a solution that can perform simple boxcar smoothing with the added requirement of accepting a boundary condition. Specifically, I need a function, either pulled from an existing library or written in Python for performance, that can h ...

An issue occurred while executing PhantomJS using Selenium's RemoteWebDriver

Launching a selenium grid hub using the default startup command: java -jar selenium-server-standalone-2.33.0.jar -role hub Also, initiating PhantomJS in its webdriver mode on the same machine with the following command: phantomjs --webdriver=8080 --web ...

Extract information from the website "angular.callbacks" using web crawling techniques

Looking to utilize R for scraping news from the following URL: "AlphaGo"&ss=fn&start=0). Below is the code I am working with: url <- "http://api.foxnews.com/v1/content/search?q=%22AlphaGo%22&fields=date,description,title,url,image,type,taxo ...

Setting parameters to Labels in Objective-C it is important to have unique

As someone new to iOS Programming, I have encountered an issue with assigning values to labels. Below is the data I receive from a service: ( { EmpName = Peter; Relation = SouthAfrica; }, { EmpName = Smith; Relation = WestIndies; }, { ...

Finding a specific number of records from an array of objects that also contain their own arrays can be achieved by using a combination of

I need a way to retrieve the last record from an ArrayList, but I'm facing a challenge because my ArrayList consists of a custom POJO class with its own array. This makes it difficult for me to determine the total number of records in the ArrayList. ...

Issue with clicking Selenium button using button.click() not resolved

Recently, I attempted to load a page and click on a button, but it seems that something is going wrong. I used to be familiar with these tasks, but the new update in Selenium has made things more challenging now. Below is the code snippet: import selenium ...

communicating between a server using node.js and a client using python or node.js using the protobuf protocol

I'm currently delving into the protobuf protocol and I've encountered an issue where the server (node js) and client (python) are experiencing difficulties exchanging messages. However, there seems to be no problem when it comes to communication ...

how to implement a collapsed row feature in an angular table row

My table contains collapsed rows with additional 2nd-level information, but not all rows have this data. Is there a way to create a controller that will display a 2nd level collapse row only if the corresponding JSON script includes 2nd level data? ...

Encountering a NoneType error while attempting to access tkinter checkbuttons within a nested dictionary

I recently set up a collection of 6 checkbuttons within my tkinter application using a for-loop. Although I have successfully created and arranged them, they are currently non-functional. The goal is to make each button influence the behavior of another fu ...

What are the benefits of incorporating "from tkinter import ttk" in your Python code?

When working with Python applications that use TK GUIs, it is common to see the following import statements being used: from tkinter import * from tkinter import ttk Now, one might wonder if calling from tkinter import ttk is redundant since ttk should a ...

Display information in an HTML table using JQuery AJAX and JSON data

As a new member and beginner learner, I have encountered some issues while trying to execute a certain task. Despite looking at similar questions, I couldn't find a solution that worked for me. What I am attempting to do is query my database to retrie ...

Guide to setting up the four axes using matplotlib

https://i.stack.imgur.com/T5BbL.png Can anyone assist me in creating a similar picture with different labels and ticks on the top and right axes? ...

Using R to retrieve values from JSON lists

My knowledge in using R is limited and I need to create a script for a school project. I have a json file with nested lists, and my task is to extract values from two specific attributes. The challenge lies in the fact that these attributes are located i ...

Tips for enhancing the parsing of arbitrary song lists

Interested in parsing tracklistings found in various formats, with lines like: artist - title artist-title artist / title artist - "title" 1. artist - title 0:00 - artist - tit le 05 artist - title 12:20 artist - title [record label] These text files ...

Issue with database setup in Django-Pytest setup_method

I am currently working on Ubuntu 14.04 with the following setup: python 2.7.6 django 1.7 [I have also tested with django 1.9] pytest-django 2.8.0 [also tried with 2.9.1] pytest 2.7.2 [also experimented with 2.8.3] Below is a snippet of the test code in ...

gorgeous stew lacks findings

Hey there, I'm a bit puzzled as to why my code isn't giving me any results even though it runs without errors. Is there a way for me to check what data is being fetched? import requests from bs4 import BeautifulSoup URL = "https://www.exped ...

Creating dynamic forms using AngularJS with a click event for the action button

I am looking to dynamically generate form fields based on the JSON structure. Currently, I have successfully rendered the fields on the webpage using a JavaScript file. However, I need assistance in adding action items to the "button" part. For example, I ...

Nested JSON object

"fid": "456", "farm_info": { "name": "Unique Farm", "address": "Unique Address", "phone": "222-222-2222", "web": "" }, "personal_info": { "name": "AnotherName", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...