【问题标题】:Best way: Facebook JSON Parse to MongoDB (Python3)最佳方式:Facebook JSON Parse to MongoDB (Python3)
【发布时间】:2017-10-23 21:03:34
【问题描述】:

我正在尝试找出将 Facebook JSON 响应解析到 MongoDB 的最佳方法。

FB 事件 JSON:

{
  "description": "Event description",
  "name": "Event name",
  "place": {
    "name": "Place name",
    "location": {
      "city": "City",
      "country": "Country",
      "latitude": -26.31604,
      "longitude": -48.83667,
      "state": "State",
      "street": "Street address",
      "zip": "000000"
    },
    "id": "429579150543987"
  },
  "start_time": "2017-10-27T19:00:00-0200",
  "id": "1557095844358825"
}

有时事件没有上述所有字段,即:locationplace 是可选的。

所以我做到了:

event_dict = {
    'id': event['id'],
    'name': event['name'],
    'start_time': event['start_time']
}

if ("place" in event):
    if ("name" in event['place']):
        event_dict['place'] = event['place']['name']
    if ("location" in event['place']):
        if ("street" in event['place']['location']):
            event_dict['street'] = event['place']['location']['street']
        if ("zip" in event['place']['location']):
            event_dict['zip'] = event['place']['location']['zip']
        if ("city" in event['place']['location']):
            event_dict['city'] = event['place']['location']['city']
        if ("state" in event['place']['location']):
            event_dict['state'] = event['place']['location']['state']
        if ("country" in event['place']['location']):
            event_dict['country'] = event['place']['location']['country']

if ("end_time" in event):
    event_dict['end_time'] = event['end_time']

if ("description" in event):
    event_dict['description'] = event['description']

event_list.append(event_dict)

event_list 是我保存在 MongoDB 上的字典列表。

我的主要问题是:有没有更好的方法来代替很多 if-then-else 条件?

【问题讨论】:

  • 所以你想要一个单级字典作为输出,该字典中有任何键值对?
  • @chasmani 是的,但原始 JSON 中的某些字段是可选的。我的代码正在运行,但我认为这不是更好的方法。

标签: python json mongodb facebook


【解决方案1】:

您可以将大部分 if 语句替换为 key: event.get("key", None) 或嵌套属性 val: event.get('key1', None).get('key2', None)

【讨论】:

    【解决方案2】:

    如果你想将 json 对象转换为 dict,那么就这样做:

    import json
    
    event_dict = json.loads(event)
    

    【讨论】:

    • 嘿,伙计。谢谢。 Buuut 我的问题是我需要更改原始结构以导入到 MongoDB。正如您在我的示例中看到的那样,原始 JSON 返回 place 的多维属性,我需要重组为一级字典(并且某些字段是可选的)。
    【解决方案3】:

    要将所有内容转换为一级字典,您可以使用递归函数来遍历字典,并在出现键值对时提取它们。像这样的:

    event = {
      "description": "Event description",
      "name": "Event name",
      "place": {
        "name": "Place name",
        "location": {
          "city": "City",
          "country": "Country",
          "latitude": -26.31604,
          "longitude": -48.83667,
          "state": "State",
          "street": "Street address",
          "zip": "000000"
        },
        "id": "429579150543987"
      },
      "start_time": "2017-10-27T19:00:00-0200",
      "id": "1557095844358825"
    }
    
    
    one_level_dict = {}
    
    def recursive_extraction(dict, base_string = ""):
        for key, value in dict.items():
            if type(value) is type({}):
                recursive_extraction(value, base_string + key + "_")
            else:
                one_level_dict[base_string + key] = value
    
    recursive_extraction(event)
    print(one_level_dict)
    

    这有点杂乱无章,但您应该能够根据自己的目的对其进行修改。

    (这是针对python3的,对于python2,我认为您需要将dict.items()替换为dict.iteritems())

    编辑:添加了一个 base_string 来维护较低级别值的 json 结构的上下文。

    【讨论】:

    • 我认为如果我在不同级别获得两个同名的键有点危险。对?不过还是谢谢!
    • @izn 我根据你的评论稍微修复了它,现在你会得到像“place_id”和“place_location_city”这样的键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 2021-04-07
    • 1970-01-01
    • 2022-12-26
    相关资源
    最近更新 更多