简体   繁体   English

Python,如何从另一个对象构建一个新的 Json 对象

[英]Python, how to build a new Json object from another one

I've got a Json object with around 10 elements in it.我有一个包含大约 10 个元素的 Json 对象。 I just need 4 of the 10 elements and would like to place the 4 elements in a new Json object.我只需要 10 个元素中的 4 个,并且想将这 4 个元素放在一个新的 Json 对象中。 I tried different ways, but only get errors.我尝试了不同的方法,但只得到错误。 My last code:我最后的代码:

import json
from pprint import pprint
import time
import datetime

def update_handler(client, update, users, chats):
    #print(update)
    message = str(update)
    data = json.loads(message)
    if data["_"] == "types.UpdateNewMessage":
        from_id = data["message"]["from_id"]
        if from_id == 390189088:
            #output message to screen
            print ("message id: ", data["message"]["id"])
            print ("date/time: ", data["message"]["date"])
            print ("from: ", data["message"]["from_id"])
            print ("message: ", data["message"]["message"])
            print ("**************")
            #output partial message to file
            json_data = {["message"]["id"],["message"]["date"],["message"]["from_id"],["message"]["message"]}
            with open('chartguysalerts.txt', 'a') as outfile:
                json.dump(json_data, outfile)

The last line of that function gives me error: TypeError: list indices must be integers or slices, not str该函数的最后一行给了我错误:类型错误:列表索引必须是整数或切片,而不是 str

I can refer to each element separately so they are valid, the output to screen works fine for example.我可以分别引用每个元素,因此它们是有效的,例如,屏幕的输出工作正常。 But i don't know how to put them together in a new shorter Json to output to a file.但我不知道如何将它们放在一个新的较短的 Json 中以输出到文件。

The easiest way would be to create a list of keys you are interested in and then use a dictionary comprehension:最简单的方法是创建您感兴趣的键列表,然后使用字典理解:

keys = ['id', 'date', 'from_id', 'message']

new_dict = {key: orig_json_dict['message'][key] for key in keys}

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

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