A
A
Alex F2018-08-22 11:48:06
Python
Alex F, 2018-08-22 11:48:06

How to add a string / ki to a json file in python?

Welcome all.
The point is this.

There is a simple table in the file:
{"values": [
      {"date": {"year": 2015,"month": 5,"day": 23},"pay": 4578,"cons": 2000},
      {"date":{"year":2018,"month":8,"day":20},"pay":810079,"cons":174349},
      {"date":{"year":2018,"month":8,"day":19},"pay":1405087,"cons":228148},
      {"date":{"year":2018,"month":8,"day":18},"pay":310057,"cons":129969},
      {"date":{"year":2018,"month":8,"day":17},"pay":666410,"cons":5717049},
      {"date":{"year":2018,"month":8,"day":16},"pay":435064,"cons":1587303},
      {"date":{"year":2018,"month":8,"day":15},"pay":217724,"cons":51281},
      {"date":{"year":2018,"month":8,"day":14},"pay":240684,"cons":43044}
]
}

This construction adds a single line at the end of the file:
a_dict = ({"date": {"year": 2011, "month": 2, "day": 2}, "pay": 810, "cons": 174})

with open('tbl.json') as f:
    data = json.load(f)

dat = data.update(a_dict)

data.update(a_dict)
with open('tbl.json', 'w') as f:
    json.dump(data, f)

And "breaks" the file.
Question: How to add rows to a table while maintaining the structure?
UPD: I don't need the code I provided. This is with stack overflow. I need help on how to append to an existing file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
JaxxDexx, 2018-08-22
@delvin-fil

a_dict = ({"date": {"year": 2011, "month": 2, "day": 2}, "pay": 810, "cons": 174}, )

with open('tbl.json') as f:
    data = json.load(f)

data["values"] += list(a_dict)

with open('tbl.json', 'w') as f:
    json.dump(data, f)

The hint is to learn the mat part - dict types, list types, and so on. json.load loads a file and in your case returns a display. Inside this mapping with the key "values" you have a list in which you need to add your element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question