简体   繁体   中英

How to get to the data in a cosmos DB document when using Function trigger on the change feed

I am using a azure function cosmos DB trigger V1 to try and parse the document take some action based on some values but I am struggling in how to read properties from the document for some reason. I am reading this page to try and understand it but cannot get it to work properly.

Documentation for trigger function

I created this sample class and it gets hit and receives the change feed just fine but I dont get inside the if clause since I am not reading the property correct and I dont really see how to get deeper into the JSON using this method

 public static class Function1
    {
        [FunctionName("Function1")]
        public static void Run([CosmosDBTrigger(
            databaseName: "XXX",
            collectionName: "XXX",
            ConnectionStringSetting = "CosmosDb",
            LeaseCollectionName = "leases", LeaseCollectionPrefix = "local")]IReadOnlyList<Document> documents, TraceWriter log)
        {
            if (documents != null && documents.Count > 0)
            {
                log.Info("Documents modified " + documents.Count);
                log.Info("First document Id " + documents[0].Id);

                foreach(var document in documents)
                {
                    if(document.GetPropertyValue<string>("sourceSystem") == "YYYY")
                    {
                        log.Info("sourceSystem = YYYY");
                    }
                }

            }
        }
    }

How do I read data from the document when it is nested deep inside a JSON array? I am a little confused about the getPropertyValue as oppose to parsing the JSON using linq or similar, How can I get my values from the document?

JSON files are parsed into Document Object, which provides method GetPropertyValue<T>(string propertyName) . We can use this method to search first level of JSON file. To get deeper, we need to parse JSON property as appropriate.

For example, to read this file.

{
    "id": "test1",
    "myJarray": [
        {
            "mydata1": "testout",
            "mydata2": "testout"
        }
    ]
}

Get inside using JArray.

foreach (var document in documents)
{
    var array = document.GetPropertyValue<JArray>("myJarray");
    if (array != null)
    {
        var data = ((JObject)array[0]).GetValue("mydata1");
        if (data != null)
        {
            log.Info(data.ToString());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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