0

I'm trying to create a Rest JSON server using python and flask as backend and JavaScript as front end, the server data need to be saved in local file but i can't seem to find a way to store the data like :

[
{'id': id, 'name': name},
<--- New record from POST request goes here
]

what i mange to do is:

def create(name, title):
    record= str({'id': id, 'name': name}) + '\n'
    rlist= open('static/notes-list.txt', 'a')
    rlist.write(note)
    rlist.close()

# Then for getting data
def get_data():
    f= open('static/notes-list.txt')
    content = f.read()
    f.close()
    data= content.strip().split('\n')
    return data

but this give me array of stings in fetch data`['{...}','{...}']

davidism
  • 121,510
  • 29
  • 395
  • 339
MaximoConn
  • 31
  • 6

2 Answers2

1

You look like you are storing rows of json (NDJSON). You can use the json package to help manage this. There are likely python packages to help manage this type of data structure as well. Check out How to open .ndjson file in Python? which might ultimately make this post a "dupe"

import json

data_file_path = "notes.txt"
id = 1

def create(name, title):
    note= {
        "id": id,
        "name": name,
        "title": title
    }

    with open(data_file_path, "a") as rlist:
        rlist.write(f"{json.dumps(note)}\n")

def get_data():
    with open(data_file_path, "r") as rlist:
        return [json.loads(row) for row in rlist]

create("foo", "bar")
create("foo2", "bar2")

data = get_data()
print(json.dumps(data, indent=4))

That should result in a file that looks like:

{"id": 1, "name": "foo", "title": "bar"}
{"id": 1, "name": "foo2", "title": "bar2"}

and data that looks like:

[
    {
        "id": 1,
        "name": "foo",
        "title": "bar"
    },
    {
        "id": 1,
        "name": "foo2",
        "title": "bar2"
    }
]
JonSG
  • 10,542
  • 2
  • 25
  • 36
-2

Try in get data() putting the f.close() after data= content.strip().spli....

Dexygen
  • 12,287
  • 13
  • 80
  • 147
KenYen-10
  • 1
  • 1
  • it does not matter as content already stored in variable – MaximoConn Mar 02 '23 at 14:54
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Friedrich Mar 07 '23 at 10:06