简体   繁体   English

动态地将python字典存储在JSON文件中

[英]Store python dictionary in JSON file dynamically

I have a python dictionary with keys in the format Aa123 and each value is a list. 我有一个python字典,其密钥格式为Aa123 ,每个值都是一个列表。 Now I need to store this data permanently in some format or in any database so that I can retrieve it easily. 现在我需要以某种格式或任何数据库永久存储这些数据,以便我可以轻松地检索它。 I thought JSON would be better for this and tried to store all the data in JSON format and then some application could use this file. 我认为JSON会更好,并尝试以JSON格式存储所有数据,然后一些应用程序可以使用此文件。 My JSON format should be like, 我的JSON格式应该是这样的,

[
  {  "firstLetter" : "A",
     "remaining" : [
        {
           "secondLetter" : "a",
           "ID" : [
              {"id" : "Aa123", "listOfItems" : ["ABC123","ASD100"]},
              {"id" : "Aa100", "listOfItems" : ["ABC123","COD101"]}
           ]
        },
        {
           "secondLetter" : "b",
           "ID" : [
              {"id" : "Ab100", "listOfItems" : ["ABC123","ASD100"]}
           ]
        }
     ]
  },
  {  "firstLetter" : "B",
     "remaining" : [
        {
           "secondLetter" : "a",
           "ID" : [                  
              {"id" : "Ba106", "listOfItems" : ["AUD123","CML101"]}
           ]
        },
        {
           "secondLetter" : "b",
           "ID" : [
              {"id" : "Bb153", "listOfItems" : ["AER113","ASD100"]},
              {"id" : "Bb100", "listOfItems" : ["ATC123","ASD500"]}
           ]
        }
     ]
  }
]

I know how to dump python dictionary into JSON, but that doesn't provide easy data query. 我知道如何将python字典转储为JSON,但这并不能提供简单的数据查询。 My question is "how to store this python dictionary(that I obtained by running a python program)in required format(like the one shown above) that makes data query easy. Thanks! 我的问题是“如何以所需的格式存储这个python字典(我通过运行python程序获得)(如上所示),使数据查询变得容易。谢谢!

It sounds like you may benefit from tinydb . 听起来你可能会受益于tinydb It stores values directly in a JSON file and provides methods for querying. 它将值直接存储在JSON文件中,并提供查询方法。

So to store your values, we do 因此,为了存储您的价值观,我们这样做

from tinydb import TinyDB, Query

db = TinyDB('test.json')
values = [{'firstLetter': 'A',
  'remaining': [{'ID': [{'id': 'Aa123', 'listOfItems': ['ABC123', 'ASD100']},
     {'id': 'Aa100', 'listOfItems': ['ABC123', 'COD101']}],
    'secondLetter': 'a'},
   {'ID': [{'id': 'Ab100', 'listOfItems': ['ABC123', 'ASD100']}],
    'secondLetter': 'b'}]},
 {'firstLetter': 'B',
  'remaining': [{'ID': [{'id': 'Ba106', 'listOfItems': ['AUD123', 'CML101']}],
    'secondLetter': 'a'},
   {'ID': [{'id': 'Bb153', 'listOfItems': ['AER113', 'ASD100']},
     {'id': 'Bb100', 'listOfItems': ['ATC123', 'ASD500']}],
    'secondLetter': 'b'}]}]
for value in values:
    db.insert(value)

To query, we do 要查询,我们这样做

>>> Q = Query()
>>> db.search(Q.firstLetter == "A")

[{'firstLetter': 'A',
  'remaining': [{'ID': [{'id': 'Aa123', 'listOfItems': ['ABC123', 'ASD100']},
     {'id': 'Aa100', 'listOfItems': ['ABC123', 'COD101']}],
    'secondLetter': 'a'},
   {'ID': [{'id': 'Ab100', 'listOfItems': ['ABC123', 'ASD100']}],
    'secondLetter': 'b'}]}]

Other than a NoSQL database like MongoDB and Cassandra , if you are using PostgreSQL, have a look at the hstore data type, specifically psycopg2's hstore functionality. 除了像MongoDBCassandra这样的NoSQL数据库之外,如果您使用的是PostgreSQL,请查看hstore数据类型,特别是psycopg2的hstore功能。 This may be of help if you want to be able to query your data more easily. 如果您希望能够更轻松地查询数据,这可能会有所帮助。

In the example below, I output the data to a JSON , and also store the dict using Shelves . 在下面的示例中,我将数据输出到JSON ,并使用Shelves存储dict

import json
import codecs
import shelve

formatted_item = {
    "data": [
      {  "firstLetter" : "A",
         "remaining" : [
            {
               "secondLetter" : "a",
               "ID" : [
                  {"id" : "Aa123", "listOfItems" : ["ABC123","ASD100"]},
                  {"id" : "Aa100", "listOfItems" : ["ABC123","COD101"]}
               ]
            },
            {
               "secondLetter" : "b",
               "ID" : [
                  {"id" : "Ab100", "listOfItems" : ["ABC123","ASD100"]}
               ]
            }
         ]
      },
      {  "firstLetter" : "B",
         "remaining" : [
            {
               "secondLetter" : "a",
               "ID" : [                  
                  {"id" : "Ba106", "listOfItems" : ["AUD123","CML101"]}
               ]
            },
            {
               "secondLetter" : "b",
               "ID" : [
                  {"id" : "Bb153", "listOfItems" : ["AER113","ASD100"]},
                  {"id" : "Bb100", "listOfItems" : ["ATC123","ASD500"]}
               ]
            }
         ]
      }
    ]
}


###
# JSON

# *** Store

output = json.dumps(dict(formatted_item), sort_keys=True, indent=4, separators=(',', ': '))
json_file_path = 'temp.json'
with codecs.open(json_file_path, 'wb', encoding='utf8') as file:
    file.write(output)

# *** Read

with open(json_file_path) as json_file:
    json_data = json.load(json_file)

# *** Print

print json_data
print json_data['data'][0]['firstLetter']


###
# Shelves

# *** Store

shelf_file_path = 'temp.log'
shelf = shelve.open(shelf_file_path)
shelf.update(formatted_item)
shelf.close()

# *** Read

loaded_shelf = shelve.open(shelf_file_path)

# *** Print

print loaded_shelf
print loaded_shelf['data'][0]['firstLetter']

You can save Python Dict objects directly on MongoDB 您可以直接在MongoDB上保存Python Dict对象

For more information, refer to this: http://api.mongodb.com/python/current/tutorial.html 有关更多信息,请参阅: http//api.mongodb.com/python/current/tutorial.html

DBMS doesn't deal with JSON query out of the box very well. DBMS不能很好地处理开箱即用的JSON查询。

You can now store JSON file in supported RDBMS, NoSQL for quick query. 您现在可以将JSON文件存储在支持的RDBMS,NoSQL中以便快速查询。 Nevertheless, DBMS that support JSON data type, try workaround by skimming the json structure and index them massively. 尽管如此,支持JSON数据类型的DBMS,通过略读json结构并大量索引它们来尝试解决方法。 NoSQL is no better than RDBMS when dealing with json data type. 在处理json数据类型时,NoSQL并不比RDBMS好。

So you must always read particular RDBMS/NoSQL documentation before storing json file, especially when you have tons of json data. 因此,在存储json文件之前,必须始终阅读特定的RDBMS / NoSQL文档,尤其是当您有大量的json数据时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM