如何在python中使用列表更新/插入键/值json对象

时间:2016-02-22 04:56:09

标签: python json

我正在尝试将多个json对象更新/插入到列表字典中。示例:插入“州”:“吉隆坡”的“城市”:“吉隆坡”和“州”:“马六甲”的“城市”:“瓜拉双溪巴鲁”。这是我的代码:

    import json
    j=[{"City": "Kuala lumpur",
    "Population (2000)": "1410300",
    "Latitude (DD)": "3.160",
    "Longitude (DD)": "101.710", 
    },
    {
            "City": "Kuala sungai baru",
            "Population (2000)": "11700",
            "Latitude (DD)": "2.350",
            "Longitude (DD)": "102.030"
    }]
    # how to update for key/value multiple json obj
    # how to insert for all json obj
    iter(j).next()['nation'] = u'malaysia' 
    #load json
    data= json.dumps(j)
    json_str= json.loads(data)
    #get key
    keys =[item['nation'] for item in json_str] # KeyError: ('nation',)

1 个答案:

答案 0 :(得分:0)

这一行

private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic;
    private static readonly Type MailWriter = typeof(SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter");
    private static readonly ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(Flags, null, new[] { typeof(Stream) }, null);
    private static readonly MethodInfo CloseMethod = MailWriter.GetMethod("Close", Flags);
    private static readonly MethodInfo SendMethod = typeof(MailMessage).GetMethod("Send", Flags);

    /// <summary>
    /// A little hack to determine the number of parameters that we
    /// need to pass to the SaveMethod.
    /// </summary>
    private static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3;

    /// <summary>
    /// The raw contents of this MailMessage as a MemoryStream.
    /// </summary>
    /// <param name="self">The caller.</param>
    /// <returns>A MemoryStream with the raw contents of this MailMessage.</returns>
    public static MemoryStream RawMessage(this MailMessage self)
    {
        var result = new MemoryStream();

        var mailWriter = MailWriterConstructor.Invoke(new object[] { result });
        SendMethod.Invoke(self, Flags, null, IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, null);
        result = new MemoryStream(result.ToArray());
        CloseMethod.Invoke(mailWriter, Flags, null, new object[] { }, null);
        return result;
    }

仅更新结构中的第一个条目。

尝试:

iter(j).next()['nation'] = u'malaysia'