【问题标题】:Parsing the pointers in JSON using python使用python解析JSON中的指针
【发布时间】:2014-06-10 00:17:40
【问题描述】:

我在具有嵌套循环的 Json 中有以下数据。这里作者有一个指向className_User的指针。

{ "results": [
{
    "accepted": "YES",
    "author": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "HZ1c6AmfuE"
    },
    "createdAt": "2014-02-19T22:39:47.899Z",
    "objectId": "t6G5lLaxoR",
    "recipient": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "avIzy6RtKQ"
    },
    "updatedAt": "2014-02-19T22:40:08.906Z"
},
{
    "accepted": "YES",
    "author": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "HZ1c6AmfuE"
    },
    "createdAt": "2014-02-20T00:18:40.640Z",
    "objectId": "ZmagKJJVKd",
    "recipient": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": "zw48k1oAw3"
    },
    "updatedAt": "2014-02-20T00:19:17.602Z"
}] }

我使用以下代码读取文件

json_data = pd.read_json('RelationshipRequest.json')
df = pd.concat([pd.DataFrame.from_dict(item, orient='index').T for item in json_data.results])
print df.author

这打印:

0    {u'className': u'_User', u'__type': u'Pointer'...
0    {u'className': u'_User', u'__type': u'Pointer'...

有没有一种方法可以从作者的嵌套字段中提取 objectId 以获取 author.objectId = HZ1c6AmfuE ?

【问题讨论】:

  • 您不使用json.load(filename)json.loads(json_string) 然后只是使用parsed_json['author']['objectid'] 的任何特殊原因?
  • 您发布的数据不是有效的 JSON 格式。我尝试使用json.load 加载它,但失败了。
  • json.load 导致“AttributeError: 'str' object has no attribute 'read'”
  • @HaiVu 成功了,>>> json.loads("""{...}""") 给了{'results': [...
  • 我的错:我复制/粘贴并错过了最后一行。

标签: python json pandas


【解决方案1】:

这就是 Python 和 JSON 的工作方式:

要么将确切的内容保存在文件中并使用:

with open('RelationshipRequest.json', 'r') as fh:
    json_data = json.load(fh)

或者你自己直接作为字符串传递:

json_data = json.loads('{ ... }')

无论哪种方式,最终结果都是(这就是您访问 JSON 数据的方式):

for result in json_data['results']:
    print(result['author']['objectId'])

Python 不会将 JSON 数据视为对象,就像您在 JavaScript 中所习惯的那样,它是一个字典,没有什么比它更短的了,所以我的建议是按照它的本质来对待。 将其转换为类对象可能有一些巧妙的技巧,但这通常是您在 Python 中实际使用 JSON 数据的方式。

【讨论】:

    【解决方案2】:

    我不完全理解你想要完成什么,但如果你想要的只是提取 objectId 字段,那么下面的代码 sn-p 会做到这一点。

    import json
    
    with open('RelationshipRequest.json') as f:
        json_data = json.load(f)
        id_list =  [rec['author']['objectId'] for rec in json_data['results']]
        print id_list
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 2023-01-26
      • 2015-06-12
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多