使用重复键Python从字符串创建一个dict / json

时间:2016-07-11 12:34:42

标签: python json string dictionary

我有一个可以解析为json或dict对象的字符串。我的字符串变量如下所示:

    my_string_variable = "{
                            "a":1,
                            "b":{
                                 "b1":1,
                                 "b2":2
                             },  
                            "b": { 
                                "b1":3, 
                                "b2":2,
                                "b4":8
                             } 
                           }"

当我json.loads(my_string_variable)时,我有一个词典但只有键的第二个值" b"保留,这是正常的,因为字典不能包含重复的密钥。

有这样的默认情况的最佳方法是什么:

    result = {
               'a':1,
               'b': [{'b1':1,'b2':2}, { 'b1':3, 'b2':2,'b4':8 } ]
             }

我已经查找了类似的问题,但他们都将dicts或列表作为输入处理,然后创建默认值来处理重复键。

在我的情况下,我有一个字符串变量,我想知道是否有一种简单的方法来实现这一点:)

谢谢^^

1 个答案:

答案 0 :(得分:4)

可以完成以下内容。

if (Request["code"] == null)
            {
                Response.Redirect(string.Format(
                    "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                    app_id, redirectUri, scope));
            }
            else
            {
                List<PublishedJobSupplier> lst = new List<PublishedJobSupplier>();
                using (CardsManagementServiceClient CMS = CardsManagementServiceClient.GetService(TransactionCode))
                {
                    lst = CMS.SuppliersListGetByPublishedJob(TransactionCode, JobId);
                }
                string groupName = lst[lst.Count - 1].SupplierName;

                Dictionary<string, string> tokens = new Dictionary<string, string>();

                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
             app_id, redirectUri, scope, Request["code"].ToString(), app_secret);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    string vals = reader.ReadToEnd();
                    foreach (string token in vals.Split('&'))
                    {
                        //meh.aspx?token1=steve&token2=jake&...  Separates tokens.
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }

                string access_token = tokens["access_token"];

                var client = new FacebookClient(access_token);
                dynamic somat = client.Get("/me/groups");
                //somat.data is array
                for (int i = 0; i < somat.data.Count; i++)
                {
                    if (somat.data[i].name == groupName)
                    {
                        client.Post("/" + somat.data[i].id + "/feed", new { message = string.Format("I am posting from the HRMS to JobId: {0} to " + groupName, hiddenJobId.Value) });
                    }
                }
   }

请注意,上面的代码取决于值类型import json def join_duplicate_keys(ordered_pairs): d = {} for k, v in ordered_pairs: if k in d: if type(d[k]) == list: d[k].append(v) else: newlist = [] newlist.append(d[k]) newlist.append(v) d[k] = newlist else: d[k] = v return d raw_post_data = '{"a":1, "b":{"b1":1,"b2":2}, "b": { "b1":3, "b2":2,"b4":8} }' newdict = json.loads(raw_post_data, object_pairs_hook=join_duplicate_keys) print (newdict) 。因此,如果原始字符串本身给出了一个列表,那么可能需要一些错误处理来使代码健壮。