Jeffail/gabs

Is there any way we can find the key in an object in a JSON file

madhurikoduru opened this issue · 2 comments

{
"ActionId": "PU",
"ActionName": "InsertACRDecision",
"BCAssetId": "54bc8609-6830-46bf-b452-2cefe7436d1b",
"BCAssetType": "ChangeRequest",
"ProjectBCAssetId": "64d3387a-daaa-4ade-ab0a-da99a9dfd5f0",
"AttributesToUpdate": {
"CRSubmissionTime": "2021-03-15T12:13:22+06:00",
"CRDecisions": [
{
"CRDecisionTime": "2022-02-11T11:11:08+06:00",
"CRDecisionNum": "1",
"CRDecisionStatus": "approve"
}
]
}
}

This is my Json . I would like to find whether there is any key with name 'CRDecisions' in AttributesToUpdate. and below is the method I am using.
func abac_accept_oneAA_on_policy(user string, AA string, p string) string {
AAObj, _ := gabs.ParseJSON([]byte(AA))
switch p {
case "InsertACRDecision":
AttributesToUpdatemap := AAObj.Path("AttributesToUpdate").Data()
AttributesToUpdate := fmt.Sprintf("%v", AttributesToUpdatemap) // find a function to find the key
if strings.Contains(AttributesToUpdate, "CRDecisions") != true {
return "Policy is not available and attributes to update is need to be modified from input"
}
}
}
So, here I am able to find the CRDecisions by checking whether the AttributesToUpdate string has the value of CRDecisions.
But I would like to know whether there is a way to find the keys CRDecisionTime and CRDecisions are present or not . Please help me with how I can approach this.

Hi @madhurikoduru! The way you described your issue makes it really, really hard for me to understand what you're trying to achieve...

Here's what I managed to put together:

package main

import (
	"log"

	"github.com/Jeffail/gabs/v2"
)

const data = `{
	"ActionId": "PU",
	"ActionName": "InsertACRDecision",
	"BCAssetId": "54bc8609-6830-46bf-b452-2cefe7436d1b",
	"BCAssetType": "ChangeRequest",
	"ProjectBCAssetId": "64d3387a-daaa-4ade-ab0a-da99a9dfd5f0",
	"AttributesToUpdate": {
		"CRSubmissionTime": "2021-03-15T12:13:22+06:00",
		"CRDecisions": [
			{
				"CRDecisionTime": "2022-02-11T11:11:08+06:00",
				"CRDecisionNum": "1",
				"CRDecisionStatus": "approve"
			}
		]
	}
}`

func main() {
	AAObj, err := gabs.ParseJSON([]byte(data))
	if err != nil {
		log.Fatalf("Failed to parse data: %s", err)
	}

	decisions := AAObj.Path("AttributesToUpdate.CRDecisions")
	decisionElements := decisions.Children()
	if len(decisionElements) == 0 {
		log.Fatal("No CRDecisions found")
	}

	for idx, decision := range decisionElements {
		if !decision.ExistsP("CRDecisionTime") {
			log.Printf("CRDecisionTime doesn't exist for decision ID %d", idx)
		}
	}
}

It handles multiple child objects in the CRDecisions array. Also, if that array is empty or if the CRDecisions key is missing entirely, you should see the "No CRDecisions found" message.

Hope that helps.

Thanks a lot. Yes that helps