【问题标题】:Python - Search and export information from JSONPython - 从 JSON 中搜索和导出信息
【发布时间】:2018-07-17 15:12:39
【问题描述】:

这是我的json文件的结构

 },
    "client1": {
        "description": "blabla",
        "contact name": "",
        "contact email": "",
        "third party organisation": "",
        "third party contact name": "",
        "third party contact email": "",
        "ranges": [
            "1.1.1.1",
            "2.2.2.2",
            "3.3.3.3"
        ]
    },
    "client2": {
        "description": "blabla",
        "contact name": "",
        "contact email": "",
        "third party organisation": "",
        "third party contact name": "",
        "third party contact email": "",
        "ranges": [
            "4.4.4.4",
            "2.2.2.2"
        ]
    },

我已经看到了导出这个 json 文件的特定部分的方法,但不是全部。基本上我想做的就是使用用户输入搜索文件。 我所苦苦挣扎的是我如何实际使用用户输入来根据输入搜索和打印 client1 或 client2 下的所有内容?我确信这只是 1 或 2 行代码,但无法弄清楚。蟒蛇新手。这是我的代码

data = json.load(open('clients.json'))

def client():
    searchq = input('Client to export: '.capitalize())
    search = ('""'+searchq+'"')
    a = open('Log.json', 'a+')
    a.write('Client: \n')

client()

【问题讨论】:

  • 您到底想搜索什么?你能举一个查询的例子和想要的结果吗?
  • 我希望能够搜索“client1”,并将其存储在一个可以附加到新文件的变量中,它应该包括 client1 下的所有字段,感谢我能得到的任何帮助! !
  • 所以您希望用户输入“client1”,然后从 JSON 中获取“client1”的信息?
  • 查看python文档处理jsondocs.python.org/2/library/json.html

标签: python json


【解决方案1】:

这应该可以帮助您:

# Safely open the file and load the data into a dictionary
with open('clients.json', 'rt') as dfile:
    data = json.load(dfile)

# Ask for the name of the client
query = input('Client to export: ')

# Show the corresponding entry if it exists,
# otherwise show a message
print(data.get(query, 'Not found'))

【讨论】:

  • 太棒了,谢谢!只需要弄清楚如何不让 pprint 按字母顺序对字段进行排序并将其附加到新文件中!谢谢!
  • 很高兴听到这个消息。如果它对您有所帮助,请考虑支持/接受答案。谢谢!
  • 没问题,再次感谢并感谢所有提供帮助的人。很棒的社区。​​span>
【解决方案2】:

我会先说这是 100% 的路过式回答,但您可以做的一件事是让您的用户使用 . (点)分隔格式,用于指定字典/json结构中键的“路径”,然后实现递归函数来查找该路径下的值,如下所示:

def get(query='', default=None, fragment=None):
    """
    Recursive function which returns the value of the terminal
    key of the query string supplied, or if no query 
    is supplied returns the whole fragment (dict).

    Query string should take the form: 'each.item.is.a.key', allowing
    the user to retrieve the value of a key nested within the fragment to
    an arbitrary depth.

    :param query: String representation of the path to the key for which
    the value should be retrieved
    :param default: If default is specified, returns instead of None if query is invalid
    :param fragment: The dictionary to inspect
    :return: value of the specified key or fragment if no query is supplied
    """
    if not query:
        return fragment

    query = query.split('.')

    try:
        key = query.pop(0)

        try:
            if isinstance(fragment, dict) and fragment:
                key = int(key) if isinstance(fragment.keys()[0], int) else key
            else:
                key = int(key)
        except ValueError:
            pass

        fragment = fragment[key]
        query = '.'.join(query)
    except (IndexError, KeyError) as e:
        return default if default is not None else None

    if not fragment:
        return fragment

    return get(query=query, default=default, fragment=fragment)

会有一百万人来到这里提出比这更好的建议,而且毫无疑问,这个功能还有很多改进之处,但既然我把它放在身边,我想我会把它放在这里,至少作为你的起点。

注意: 片段可能应该作为位置参数或其他东西。身份证。这不是因为我不得不删除一些特定于应用程序的上下文(它曾经有一个合理的默认状态)而且我不想开始重写东西,所以我把它留给你。

你可以用这个函数做一些很酷的事情,给定一些数据:

d = {
    'woofage': 1,
    'woofalot': 2,
    'wooftastic': ('woof1', 'woof2', 'woof3'),
    'woofgeddon': {
         'woofvengers': 'infinity woof'
    }
}

试试这些:

get(fragment=d, query='woofage')
get(fragment=d, query='wooftastic')
get(fragment=d, query='wooftastic.0')
get(fragment=d, query='woofgeddon.woofvengers')
get(fragment=d, query='woofalistic', default='ultraWOOF')

一路顺风!

【讨论】:

    【解决方案3】:

    将 json 格式传入 Dict,然后查看您想要的主题并读取或写入它

    import json
    r = {'is_claimed': True, 'rating': 3.5} 
    r = json.dumps(r) # Here you have json format {"is_claimed": true, "rating": 3.5}
    

    Json 到字典:

    loaded_r = json.loads(r) # {'is_claimed': True, 'rating': 3.5}
    
    print (r)#Print json format
    print (loaded_r)  #Print dict
    

    阅读主题

    Data=loaded_r['is_claimed'] #Print Topic desired
    print(Data) #True
    

    覆盖主题

    loaded_r['is_claimed']=False
    

    这也会做同样的事情

    print(loaded_r['client1']['description'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2019-05-15
      相关资源
      最近更新 更多