Chen
Chen

Reputation: 181

Storing JSON value into a dictionary with ordered key name

This is a question based on How to iterate through a dictionary to get and pass key name to string, the given code below iterates through a JSON, getting key-names and JArray index and passing them orderly to strings of JSON paths, finally it returns a Dictionary(ordered string, JsonValue), the dictionary key-name is expected to be ordered like "key1:key1-1:0", which means desiredDictionary["key1:key1-1:0"] = commonDictionary["key1"]["key1-1"][0].

According to the JSON below, if "Five": {"ArrayInFive": ["elem1", "elem2"]} is deleted, it works fine.

C# code

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
......
static void Main(string[] args)
        {
            var json = File.ReadAllText(@myJsonPath);
            var jObj = JsonConvert.DeserializeObject<JObject>(json);

            var desiredDict = FlattenJObjectToDictionary(jObj);


            foreach (var key in desiredDict.Keys)
            {
                Console.WriteLine(key + " : " + desiredDict[key]);
            }


            Console.Read();
        }

        private static IDictionary<string, string> FlattenJObjectToDictionary(JObject obj)
        {
            // obtain a key/value enumerable and convert it to a dictionary
            return NestedJObjectToFlatEnumerable(obj, null).ToDictionary(kv => kv.Key, kv => kv.Value);
        }


        private static IEnumerable<KeyValuePair<string, string>> NestedJObjectToFlatEnumerable(object data, string path = null)
        {
            JObject jObject = (JObject)data;
            var jOP = jObject.Properties();
            foreach (var jop in jOP)
            {
                if (jop.Value is JObject)
                {
                    var child = (JObject)jop.Value;

                    // build the child path based on the root path and the property name
                    string childPath = path != null ? string.Format("{0}{1}:", path, jop.Name) : string.Format("{0}:", jop.Name);

                    // get each result from our recursive call and return it to the caller
                    foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
                    {
                        yield return resultVal;
                    }
                }
                else if (jop.Value is JArray)
                {
                    var jArray = (JArray)jop.Value;
                    for (int i = 0; i < jArray.Count; i++)
                    {
                        var child = jArray[i];

                        // build the child path based on the root path and the JArray index
                        string childPath = path != null ? string.Format("{0}{1}:{2}:", path, jop.Name, i.ToString()) : string.Format("{0}:{1}:", jop.Name, i.ToString());

                        // get each result from our recursive call and return it to the caller
                        foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
                        {
                            yield return resultVal;
                        }
                    }
                }
                else
                {
                    // this kind of assumes that all values will be convertible to string, so you might need to add handling for other value types
                    yield return new KeyValuePair<string, string>(string.Format("{0}{1}", path, Convert.ToString(jop.Name)), Convert.ToString(jop.Value));
                }
            }

        }

JSON

{
    "One": "Hey",
    "Two": {
        "Two": "HeyHey"
           },
    "Three": {
        "Three": {
            "Three": "HeyHeyHey"    
                 }
              }, 
    "Four": [
            {
            "One": "Hey"
            },
            {
            "Two": 
                {
            "Two": "HeyHey"
                }
            }
            ],
    "Five": {
        "ArrayInFive": [ "elem1", "elem2" ]
            }
}

I expect

desiredDictionary["Five"]["ArrayInFive"][0] = "elem1"

and

desiredDictionary["Five"]["ArrayInFive"][1] = "elem2"

But exception of being "unable to convert JValue to JObject" pops out, I need some help with the code correction, maybe the whole program.

Upvotes: 1

Views: 125

Answers (1)

samgak
samgak

Reputation: 24417

Change your handling of JArray objects in NestedJObjectToFlatEnumerable to this:

else if (jop.Value is JArray)
{
    var jArray = (JArray)jop.Value;
    for (int i = 0; i < jArray.Count; i++)
    {
        var child = jArray[i];

        if (child is JValue)
        {
            // return JValue objects directly as array elements instead of as objects in the array with their own property-value pairs
            yield return new KeyValuePair<string, string>(string.Format("{0}{1}:{2}", path, jop.Name, i.ToString()), Convert.ToString(((JValue)child).Value));
        }
        else
        {
            // build the child path based on the root path and the JArray index
            string childPath = path != null ? string.Format("{0}{1}:{2}:", path, jop.Name, i.ToString()) : string.Format("{0}:{1}:", jop.Name, i.ToString());

            // get each result from our recursive call and return it to the caller
            foreach (var resultVal in NestedJObjectToFlatEnumerable(child, childPath))
            {
                yield return resultVal;
            }
        }
    }
}

This handles the case where an array element is a JValue instead of an object with it's own property-value pairs by returning the element as a property of the array with a property name given by the array index (concatenated onto the array path).

Upvotes: 1

Related Questions