pythonjsonpython-3.xkivyjsonstore

Kivy: Add JSON Object inside another JSON Object using kivy.storage.jsonstore


I'm New on kivy. I want to save my settings of KivyApplication in a JSON file.

I want to create a JSON file like this:

{
  "users": [
    {
      "user_name": "person_1",
      "password": "1234"
    },
    {
      "user_name": "person_2",
      "password": "5678"
    }
  ]
}

I found an example in Kivy API references web page (Kivy JSON Storage Example).

Here is my solution for add multiple JSON Objects to the Main JSON Object:

JsonStore.py:

from kivy.storage.jsonstore import JsonStore

store = JsonStore('hello.json')

users_list = [{"user_name": "person_1", "password": "1234"},
              {"user_name": "person_2", "password": "5678"}]
# put some values
for u in users_list:
    print(u)
    store.put('users', u)

But this error occur:

store.put('users', u)
TypeError: put() takes 2 positional arguments but 3 were given

Does anyone know what am I doing wrong here and how to make this work? Thank you in advance...


Solution

  • The structure is kind of predefined by put(object_name, attribute1=value1[, attribute2=value2, ...]).

    To accomplish what you want, you have to give users a key to hold your list of objects.

    Long story short, this code should work:

    from kivy.storage.jsonstore import JsonStore
    
    store = JsonStore('hello.json')
    
    users_list = [{"user_name": "person_1", "password": "1234"},
              {"user_name": "person_2", "password": "5678"}]
    
    store.put('users', objects=users_list)