Skip to content

json_parser

Module providing JSON parsing capabilities for the CAFEX framework.

This module provides robust JSON parsing and manipulation functionality including: - Reading and validating JSON data - Extracting values using keys or key paths - Comparing JSON structures - Converting JSON to XML - Updating JSON data based on keys

ParseJsonData

A modern JSON parser for extracting, comparing, and manipulating JSON data.

This class provides methods to parse JSON content and extract data using various techniques including key lookup, path-based access, and nested searches. It also supports comparison, validation, and manipulation of JSON data.

Features
  • JSON file and string parsing
  • Key and path-based value extraction
  • Nested structure traversal
  • JSON comparison functionality
  • JSON to XML conversion
  • JSON validation
  • JSON manipulation and updating

Attributes:

Name Type Description
logger

Logger instance for debug/error logging

exceptions

Exception handler for standardized error handling

Example

parser = ParseJsonData() json_data = parser.read_json_file("config.json") value = parser.get_value(json_data, "api_key")

Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
class ParseJsonData:
    """
    A modern JSON parser for extracting, comparing, and manipulating JSON data.

    This class provides methods to parse JSON content and extract data using various techniques
    including key lookup, path-based access, and nested searches. It also supports comparison,
    validation, and manipulation of JSON data.

    Features:
        - JSON file and string parsing
        - Key and path-based value extraction
        - Nested structure traversal
        - JSON comparison functionality
        - JSON to XML conversion
        - JSON validation
        - JSON manipulation and updating

    Attributes:
        logger: Logger instance for debug/error logging
        exceptions: Exception handler for standardized error handling

    Example:
        >>> parser = ParseJsonData()
        >>> json_data = parser.read_json_file("config.json")
        >>> value = parser.get_value(json_data, "api_key")
    """

    def __init__(self):
        self.logger = CoreLogger(name=__name__).get_logger()
        self.exceptions = CoreExceptions()

    def get_value(self, json_dict: Dict[str, Any], key: str) -> Any:
        """
        Gets the value of a key from the first level of a JSON dictionary.

        Args:
            json_dict (dict): The JSON dictionary to search.
            key (str): The key to retrieve the value for.

        Returns:
            The value associated with the key, or None if not found.

        Raises:
            ValueError: If json_dict is not a dictionary or the key is not found.

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"name": "John", "age": 30}
            >>> parser.get_value(data, "name")
            'John'
        """
        if not isinstance(json_dict, dict):
            self.exceptions.raise_generic_exception(
                "json_dict must be a dictionary", fail_test=False
            )
            return None

        if not key:
            self.exceptions.raise_generic_exception("key cannot be null or empty", fail_test=False)
            return None

        try:
            return json_dict[key]
        except KeyError:
            self.exceptions.raise_generic_exception(
                f"Key '{key}' not in the JSON dictionary", fail_test=False
            )
            return None

    def get_value_of_key_path(
        self, json_dict: Dict[str, Any], key_path: str, delimiter: str = "/"
    ) -> Any:
        """
        Gets the value of a key from a nested JSON dictionary using the provided key path.

        Args:
            json_dict (dict): The JSON dictionary to search.
            key_path (str): The path to the key, using the specified delimiter.
            delimiter (str, optional): The delimiter used in the key path (default: "/").

        Returns:
            Any: The value associated with the key path, or None if not found.

        Raises:
            ValueError: If json_dict is not a dictionary or the key path is not found.

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"user": {"profile": {"name": "John"}}}
            >>> parser.get_value_of_key_path(data, "user/profile/name")
            'John'
            >>> parser.get_value_of_key_path(data, "user.profile.name", ".")
            'John'
        """
        try:
            if not isinstance(json_dict, dict):
                self.exceptions.raise_generic_exception(
                    "json_dict must be a dictionary", fail_test=False
                )
                return None

            if not key_path:
                self.exceptions.raise_generic_exception(
                    "key_path cannot be null or empty", fail_test=False
                )
                return None
            # Split the key path into segments
            key_list = key_path.split(delimiter)

            def get_item(obj, key):
                if isinstance(obj, list) and key.isdigit():
                    # Convert string index to integer for list access
                    return obj[int(key)]
                return obj[key]

            return reduce(get_item, key_list, json_dict)
        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in fetching key value using the provided key path: {str(e)}",
                fail_test=False,
            )
            return None

    def read_json_file(self, file_path: str) -> Dict[str, Any]:
        """
        Reads a JSON file and returns the parsed dictionary.

        Args:
            file_path: The path to the JSON file.

        Returns:
            The parsed JSON dictionary.

        Raises:
            FileNotFoundError: If the JSON file is not found.
            ValueError: If the JSON file contains invalid JSON.

        Examples:
            >>> parser = ParseJsonData()
            >>> data = parser.read_json_file("config.json")
            >>> print(data["version"])
            '1.0'
        """
        try:
            if not os.path.exists(file_path):
                self.exceptions.raise_generic_exception(
                    f"JSON file not found: {file_path}", fail_test=False
                )
                return {}

            with open(file_path, "r", encoding="utf-8") as json_file:
                return json.load(json_file)
        except json.JSONDecodeError as e:
            self.exceptions.raise_generic_exception(
                f"Error parsing JSON file: {str(e)}", fail_test=False
            )
            return {}
        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error reading JSON file: {str(e)}", fail_test=False
            )
            return {}

    def get_value_of_key(
        self, json_data: Union[str, Dict[str, Any]], key: str, nested: bool = False
    ) -> Any:
        """
        Gets the value of a key from the JSON data, optionally searching nested structures.

        Args:
            json_data: The JSON data to parse (either a string or a dictionary).
            key: The key to retrieve the value for.
            nested: Whether to search for the key in nested structures (default: False).

        Returns:
            The value associated with the key, or a list of values if nested is True and multiple keys are found.

        Raises:
            ValueError: If json_data is not a dictionary or the key is not found.

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"user": {"name": "John"}, "admin": {"name": "Admin"}}
            >>> parser.get_value_of_key(data, "user", False)
            {'name': 'John'}
            >>> parser.get_value_of_key(data, "name", True)
            ['John', 'Admin']
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return None if not nested else []

            if not key:
                self.exceptions.raise_generic_exception(
                    "key cannot be null or empty", fail_test=False
                )
                return None if not nested else []

            json_dict = self.get_dict(json_data)

            if nested:
                return nested_lookup(key, json_dict)

            return self.get_value(json_dict, key)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error getting value of key: {str(e)}", fail_test=False
            )
            return None if not nested else []

    def get_json_values_by_key_path(
        self,
        json_data: Union[str, Dict[str, Any]],
        delimiter: str = "/",
        keypath: Optional[str] = None,
        key: Optional[str] = None,
        parser: bool = False,
    ) -> Any:
        """
        Extracts values from a JSON dictionary using a key path.

        Args:
            json_data: The JSON data (string or dictionary)
            delimiter: The delimiter used in the key path
            keypath: The key path to extract values from
            key: The specific sub-child key to retrieve the value for
            parser: If True, parses the json_data as a JSON string before processing

        Returns:
            Any: The value(s) associated with the key path.

        Raises:
            ValueError: If json_data or keypath is null or empty, or if key is not found
            in the nested dictionary

        Examples:
            >>> json_parser = ParseJsonData()
            >>> data = {"users": {"admin": {"name": "Admin", "role": "admin"}}}
            >>> json_parser.get_json_values_by_key_path(data, keypath="users/admin", key="name")
            'Admin'
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception("json_data cannot be null", fail_test=False)
                return None

            json_dict = self.get_dict(json_data)

            if parser:
                if not keypath:
                    self.exceptions.raise_generic_exception(
                        "keypath cannot be null when parser is True", fail_test=False
                    )
                    return None

                modified_keypath = keypath.replace("/", ".") if delimiter == "/" else keypath
                json_tree = objectpath.Tree(json_dict)
                return json_tree.execute("$." + modified_keypath)

            if keypath:
                root_parent = keypath.split(delimiter)

                if len(root_parent) == 1:
                    root = root_parent[0]
                    if root not in json_dict:
                        self.exceptions.raise_generic_exception(
                            f"Key '{root}' not found in JSON data", fail_test=False
                        )
                        return None

                    result = json_dict[root]
                    # If we're looking for a specific subkey within this result
                    if key is not None and isinstance(result, dict):
                        return result.get(key)
                    return result

                root = root_parent[0]
                parent = root_parent[1]

                if root not in json_dict:
                    self.exceptions.raise_generic_exception(
                        f"Root key '{root}' not found in JSON data", fail_test=False
                    )
                    return None

                json_tree = objectpath.Tree(json_dict[root])
                result_list = list(json_tree.execute("$.." + parent))

                for result in result_list:
                    if key is not None and isinstance(result, dict):
                        return result.get(key)
                    return result

            self.exceptions.raise_generic_exception(
                "Invalid arguments for get_json_values_by_key_path", fail_test=False
            )
            return None

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in get_json_values_by_key_path: {str(e)}", fail_test=False
            )
        return None

    def get_value_from_key_path(
        self,
        json_data: Union[str, Dict[str, Any]],
        key_path: str,
        key_path_type: str,
        key: Optional[str] = None,
        delimiter: str = "/",
    ) -> Any:
        """
        Extract the value at the specified key path from the JSON data.

        Args:
            json_data: The JSON data (string or dictionary)
            key_path: The path to the key, using the specified delimiter
            key_path_type: Either "absolute" or "relative"
            key: The key to retrieve the value for when using relative key paths
            delimiter: The delimiter used in the key path

        Returns:
            The value associated with the key path

        Raises:
            ValueError: If required arguments are missing, invalid, or the key path is not found

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"users": {"admin": {"name": "Admin", "role": "admin"}}}
            >>> parser.get_value_from_key_path(
            ...     data, "users/admin", "absolute"
            ... )
            {'name': 'Admin', 'role': 'admin'}
            >>> parser.get_value_from_key_path(
            ...     data, "users/admin", "relative", "name"
            ... )
            'Admin'
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception("json_data cannot be null", fail_test=False)
                return None

            if not key_path:
                self.exceptions.raise_generic_exception("key_path cannot be null", fail_test=False)
                return None

            if not key_path_type:
                self.exceptions.raise_generic_exception(
                    "key_path_type cannot be null", fail_test=False
                )
                return None

            json_dict = self.get_dict(json_data)

            key_path_type = key_path_type.lower()

            if key_path_type == "absolute":
                return self.get_value_of_key_path(json_dict, key_path, delimiter)
            if key_path_type == "relative":
                if key is None:
                    self.exceptions.raise_generic_exception(
                        "key argument is required if key_path_type is relative", fail_test=False
                    )
                    return None

                return self.get_json_values_by_key_path(
                    json_dict, delimiter, keypath=key_path, key=key
                )

            self.exceptions.raise_generic_exception(
                "Invalid key_path_type. Use 'absolute' or 'relative'", fail_test=False
            )
            return None

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in get_value_from_key_path: {str(e)}", fail_test=False
            )
            return None

    def print_all_key_values(self, json_data: Dict[str, Any]) -> None:
        """
        Print all key-value pairs in a nested dictionary structure.

        Args:
            json_data: The nested dictionary to print

        Raises:
            ValueError: If json_data is not a dictionary

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"user": {"name": "John", "age": 30}}
            >>> parser.print_all_key_values(data)
            user:
              name: John
              age: 30
        """
        try:
            if not isinstance(json_data, dict):
                self.exceptions.raise_generic_exception(
                    "json_data must be a dictionary", fail_test=False
                )
                return

            def _print_nested(data: Dict[str, Any], indent: int = 0) -> None:
                for key, value in data.items():
                    if isinstance(value, dict):
                        self.logger.debug("%s%s:", " " * indent, key)
                        _print_nested(value, indent + 2)
                    else:
                        self.logger.debug("%s%s: %s", " " * indent, key, value)

            _print_nested(json_data)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error while printing all key-value pairs: {str(e)}", fail_test=False
            )

    def get_dict(self, json_data: Union[str, Dict[str, Any]]) -> Dict[str, Any]:
        """
        Ensure the input is a valid JSON dictionary.

        Args:
            json_data: The input data, which can be either a JSON string or a dictionary

        Returns:
            The parsed JSON dictionary

        Raises:
            ValueError: If the input data is not a valid JSON string or dictionary

        Examples:
            >>> parser = ParseJsonData()
            >>> parser.get_dict('{"name": "John"}')
            {'name': 'John'}
            >>> parser.get_dict({"name": "John"})
            {'name': 'John'}
        """
        try:
            if isinstance(json_data, dict):
                return json_data

            if isinstance(json_data, str):
                return json.loads(json_data)

            self.exceptions.raise_generic_exception(
                "Input must be a JSON string or dictionary", fail_test=False
            )
            return {}

        except json.JSONDecodeError as e:
            self.exceptions.raise_generic_exception(f"Invalid JSON data: {str(e)}", fail_test=False)
            return {}
        except Exception as e:
            self.exceptions.raise_generic_exception(f"Error in get_dict: {str(e)}", fail_test=False)
            return {}

    def is_json(self, json_data: str) -> Dict[str, Any]:
        """
        Check if the input is a valid JSON string and return the parsed dictionary.

        Args:
            json_data: The input data to be checked

        Returns:
            The parsed JSON dictionary if json_data is valid JSON

        Raises:
            ValueError: If the input data is not valid JSON

        Examples:
            >>> parser = ParseJsonData()
            >>> parser.is_json('{"name": "John"}')
            {'name': 'John'}
            >>> parser.is_json('invalid')
            Traceback (most recent call last):
            ...
            ValueError: Invalid JSON data: ...
        """

        try:
            return json.loads(json_data)
        except json.JSONDecodeError as e:
            self.exceptions.raise_generic_exception(f"Invalid JSON data: {str(e)}", fail_test=False)
            return {}

    def compare_json(
        self,
        expected_json: Union[str, Dict[str, Any]],
        actual_json: Union[str, Dict[str, Any]],
        ignore_keys: Optional[List[str]] = None,
        ignore_extra: bool = False,
    ) -> Union[bool, Tuple[bool, List[str]]]:
        """
        Compare two JSON structures (strings or dictionaries).

        Args:
            expected_json: The expected JSON data (string or dictionary)
            actual_json: The actual JSON data (string or dictionary)
            ignore_keys: A list of keys to ignore during comparison
            ignore_extra: Whether to ignore extra keys in actual_json

        Returns:
            True if the JSON structures are equal (considering ignore_keys and ignore_extra),
            otherwise a tuple containing False and a list of mismatches

        Raises:
            ValueError: If the input JSON data is invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> parser.compare_json(
            ...     {"name": "John", "age": 30},
            ...     {"name": "John", "age": 30, "role": "admin"},
            ...     ignore_extra=True
            ... )
            True
            >>> result = parser.compare_json(
            ...     {"name": "John", "age": 30},
            ...     {"name": "John", "age": 25}
            ... )
            >>> isinstance(result, tuple) and not result[0]
            True
        """

        try:
            if ignore_keys is None:
                ignore_keys = []

            if expected_json is None:
                self.exceptions.raise_generic_exception(
                    "expected_json can not be None", fail_test=False
                )
                return False, ["expected_json can not be None"]

            if actual_json is None:
                self.exceptions.raise_generic_exception(
                    "actual_json can not be None", fail_test=False
                )
                return False, ["actual_json can not be None"]

            if not isinstance(ignore_keys, list):
                self.exceptions.raise_generic_exception(
                    "ignore_keys must be a list", fail_test=False
                )
                return False, ["ignore_keys must be a list"]

            if not isinstance(ignore_extra, bool):
                self.exceptions.raise_generic_exception(
                    "ignore_extra must be a boolean", fail_test=False
                )
                return False, ["ignore_extra must be a boolean"]

            expected_dict = self.get_dict(expected_json)
            actual_dict = self.get_dict(actual_json)

            error_list = []

            def compare_dicts(
                expected: Dict[str, Any], actual: Dict[str, Any], path: str = ""
            ) -> None:
                for key, expected_value in expected.items():
                    if key in ignore_keys:
                        continue

                    if key not in actual:
                        error_list.append(f"Key '{path}{key}' does not exist in actual JSON")
                        continue

                    actual_value = actual[key]

                    if isinstance(expected_value, dict) and isinstance(actual_value, dict):
                        compare_dicts(expected_value, actual_value, f"{path}{key}.")
                    elif isinstance(expected_value, list) and isinstance(actual_value, list):
                        if len(expected_value) != len(actual_value):
                            error_list.append(
                                f"List length mismatch for '{path}{key}': "
                                f"expected {len(expected_value)}, got {len(actual_value)}"
                            )
                        else:
                            for i, (exp_item, act_item) in enumerate(
                                zip(expected_value, actual_value)
                            ):
                                if isinstance(exp_item, dict) and isinstance(act_item, dict):
                                    compare_dicts(exp_item, act_item, f"{path}{key}[{i}].")
                                elif exp_item != act_item:
                                    error_list.append(
                                        f"Value mismatch at '{path}{key}[{i}]': "
                                        f"expected {exp_item}, got {act_item}"
                                    )
                    elif expected_value != actual_value:
                        error_list.append(
                            f"Value mismatch for '{path}{key}': "
                            f"expected {expected_value}, got {actual_value}"
                        )

                if not ignore_extra:
                    for key in set(actual.keys()) - set(expected.keys()):
                        if key not in ignore_keys:
                            error_list.append(f"Unexpected key in actual JSON: '{path}{key}'")

            compare_dicts(expected_dict, actual_dict)

            if error_list:
                return False, error_list

            return True

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error comparing JSON objects: {str(e)}", fail_test=False
            )
            return False, [f"Error comparing JSON objects: {str(e)}"]

    def level_based_value(
        self, json_data: Union[str, Dict[str, Any]], key: str, level: int = 0
    ) -> List[Any]:
        """
        Get values for a key at a specific level in a nested JSON structure.

        Args:
            json_data: The JSON data (string or dictionary)
            key: The key to search for
            level: The level in the JSON hierarchy to search (0-based)

        Returns:
            A list of values found for the key at the specified level

        Raises:
            ValueError: If json_data or key is null or empty, or if level is not an integer

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {
            ...     "level0": "value0",
            ...     "nested": {
            ...         "level1": "value1",
            ...         "more": {
            ...             "level2": "value2"
            ...         }
            ...     }
            ... }
            >>> parser.level_based_value(data, "level0", 0)
            ['value0']
            >>> parser.level_based_value(data, "level1", 1)
            ['value1']
            >>> parser.level_based_value(data, "level2", 2)
            ['value2']
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return []

            if not key:
                self.exceptions.raise_generic_exception(
                    "key cannot be null or empty", fail_test=False
                )
                return []

            if not isinstance(level, int):
                self.exceptions.raise_generic_exception("level must be an integer", fail_test=False)
                return []

            json_dict = self.get_dict(json_data)

            def search_at_level(
                data: Any, search_key: str, current_level: int, target_level: int
            ) -> List[Any]:
                results = []

                if isinstance(data, dict):
                    for k, v in data.items():
                        if k == search_key and current_level == target_level:
                            results.append(v)

                        if isinstance(v, (dict, list)) and current_level < target_level:
                            results.extend(
                                search_at_level(v, search_key, current_level + 1, target_level)
                            )
                elif isinstance(data, list):
                    for item in data:
                        if isinstance(item, (dict, list)):
                            results.extend(
                                search_at_level(item, search_key, current_level, target_level)
                            )

                return results

            return search_at_level(json_dict, key, 0, level)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in level_based_value: {str(e)}", fail_test=False
            )
            return []

    def convert_json_to_xml(self, json_data: Union[str, Dict[str, Any]]) -> str:
        """
        Convert a JSON string/dict to an XML string.

        Args:
            json_data: The JSON string/dict to convert

        Returns:
            The XML string

        Raises:
            ValueError: If the input JSON is invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> xml = parser.convert_json_to_xml({"name": "John", "age": 30})
            >>> "<name>John</name>" in xml and "<age>30</age>" in xml
            True
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return ""

            json_dict = self.get_dict(json_data)
            xml_str = dicttoxml.dicttoxml(json_dict, custom_root="all", attr_type=False)
            return xml_str.decode()

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error converting JSON to XML: {str(e)}", fail_test=False
            )
            return ""

    def get_all_keys(self, json_data: Union[str, Dict[str, Any]]) -> List[str]:
        """
        Extract all keys from a nested JSON dictionary as a list.

        Args:
            json_data: The JSON data (string or dictionary)

        Returns:
            A list of all keys found in the JSON data

        Raises:
            ValueError: If the input JSON data is invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> keys = parser.get_all_keys({"user": {"name": "John", "age": 30}})
            >>> sorted(keys)
            ['age', 'name', 'user']
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return []

            json_dict = self.get_dict(json_data)
            return get_all_keys(json_dict)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error getting all keys: {str(e)}", fail_test=False
            )
            return []

    def get_occurrence_of_key(self, json_data: Union[str, Dict[str, Any]], key: str) -> int:
        """
        Count the occurrences of a key in the JSON data.

        Args:
            json_data: The JSON data (string or dictionary)
            key: The key to count occurrences of

        Returns:
            The number of occurrences of the key

        Raises:
            ValueError: If the input JSON data is invalid or the key is empty

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"name": "John", "address": {"name": "Home", "street": "Main St"}}
            >>> parser.get_occurrence_of_key(data, "name")
            2
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return 0

            if not key:
                self.exceptions.raise_generic_exception(
                    "key cannot be null or empty", fail_test=False
                )
                return 0

            json_dict = self.get_dict(json_data)
            return get_occurrence_of_key(json_dict, key)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error getting occurrence of key: {str(e)}", fail_test=False
            )
            return 0

    def key_exists(self, json_data: Union[str, Dict[str, Any]], key: str) -> bool:
        """
        Check if a key exists in the JSON data.

        Args:
            json_data: The JSON data (string or dictionary)
            key: The key to check for

        Returns:
            True if the key exists, False otherwise

        Raises:
            ValueError: If the input JSON data is invalid or the key is empty

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"name": "John", "age": 30}
            >>> parser.key_exists(data, "name")
            True
            >>> parser.key_exists(data, "email")
            False
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return False

            if not key:
                self.exceptions.raise_generic_exception(
                    "key cannot be null or empty", fail_test=False
                )
                return False

            all_keys = self.get_all_keys(json_data)
            return key in all_keys

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error checking if key exists: {str(e)}", fail_test=False
            )
            return False

    def get_multiple_key_value(
        self,
        json_data: Union[str, Dict[str, Any]],
        keys: List[str],
        key_paths: Optional[List[str]] = None,
        delimiter: str = "/",
    ) -> Dict[str, Any]:
        """
        Get values for multiple keys and key paths from the JSON data.

        Args:
            json_data: The JSON data (string or dictionary)
            keys: List of keys for which to fetch values
            key_paths: Optional list of key paths for which to fetch values
            delimiter: The delimiter used in the key paths

        Returns:
            A dictionary mapping keys and key paths to their values

        Raises:
            ValueError: If json_data or keys is null or keys is not a list

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"user": {"profile": {"name": "John", "age": 30}}}
            >>> results = parser.get_multiple_key_value(
            ...     data, ["user"], key_paths=["user/profile", "user/profile/name"]
            ... )
            >>> "user" in results and "user/profile" in results and "user/profile/name" in results
            True
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return {}

            if not keys:
                self.exceptions.raise_generic_exception(
                    "keys cannot be null or empty", fail_test=False
                )
                return {}

            if not isinstance(keys, list):
                self.exceptions.raise_generic_exception("keys must be a list", fail_test=False)
                return {}

            result = {}
            json_dict = self.get_dict(json_data)

            # Get values for keys
            for key in keys:
                result[key] = nested_lookup(key, json_dict)

            # Get values for key paths
            if key_paths:
                for key_path in key_paths:
                    try:
                        result[key_path] = self.get_value_of_key_path(
                            json_dict, key_path, delimiter
                        )
                    except Exception as e:
                        self.logger.warning(
                            "Error getting value for key path '%s': %s", key_path, str(e)
                        )
                        result[key_path] = None

            return result

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error getting multiple key values: {str(e)}", fail_test=False
            )
            return {}

    def get_json_result(
        self,
        json_data: Union[str, Dict[str, Any]],
        key: Optional[str] = None,
        nested: bool = False,
        keypath: Optional[str] = None,
        keypath_type: Optional[str] = None,
        key_input: Optional[str] = None,
        delimiter: str = "/",
    ) -> Any:
        """
        Get a value from JSON data based on key or key path.

        This method is a convenience wrapper that provides a unified interface to retrieve
        values using either simple keys or complex key paths.

        Args:
            json_data: The JSON data (string or dictionary)
            key: The key to retrieve the value for (for simple key lookups)
            nested: Whether to search for the key in nested structures (when using key)
            keypath: The path to the key, using the specified delimiter (for path-based lookups)
            keypath_type: Either "absolute" or "relative" (required when using keypath)
            key_input: The specific sub-child key to retrieve the value for (when using relative keypath)
            delimiter: The delimiter used in the key path (default: "/")

        Returns:
            The value associated with the key or key path

        Raises:
            ValueError: If required parameters are missing or invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"user": {"profile": {"name": "John"}}}
            >>> # Simple key lookup
            >>> parser.get_json_result(data, key="user")
            {'profile': {'name': 'John'}}
            >>> # Nested key lookup
            >>> parser.get_json_result(data, key="name", nested=True)
            ['John']
            >>> # Absolute key path lookup
            >>> parser.get_json_result(
            ...     data,
            ...     keypath="user/profile/name",
            ...     keypath_type="absolute"
            ... )
            'John'
            >>> # Relative key path lookup
            >>> parser.get_json_result(
            ...     data,
            ...     keypath="user/profile",
            ...     keypath_type="relative",
            ...     key_input="name"
            ... )
            'John'
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return None

            # Simple key lookup
            if key is not None:
                return self.get_value_of_key(json_data, key, nested)

            # Key path lookup
            if keypath is not None:
                if not keypath_type:
                    self.exceptions.raise_generic_exception(
                        "keypath_type is required when using keypath", fail_test=False
                    )
                    return None

                return self.get_value_from_key_path(
                    json_data=json_data,
                    key_path=keypath,
                    key_path_type=keypath_type,
                    key=key_input,
                    delimiter=delimiter,
                )

            self.exceptions.raise_generic_exception(
                "Either key or keypath must be provided", fail_test=False
            )
            return None

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in get_json_result: {str(e)}", fail_test=False
            )
            return None

    def update_json_based_on_key(
        self, json_data: Union[str, Dict[str, Any]], key: str, updated_value: Any
    ) -> Dict[str, Any]:
        """
        Update all occurrences of a key in the JSON data with a new value.

        Args:
            json_data: The JSON data (string or dictionary)
            key: The key to update
            updated_value: The new value for the key

        Returns:
            The updated JSON dictionary
            The same JSON dictionary if key is empty or key doesn't exist in the JSON data

        Raises:
            ValueError: If json_data is invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"name": "John", "user": {"name": "John"}}
            >>> updated = parser.update_json_based_on_key(data, "name", "Jane")
            >>> updated["name"] == "Jane" and updated["user"]["name"] == "Jane"
            True
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return {}

            json_dict = self.get_dict(json_data)

            if not key:
                self.exceptions.raise_generic_exception(
                    "key cannot be null or empty", fail_test=False
                )
                return json_dict

            if not self.key_exists(json_dict, key):
                self.exceptions.raise_generic_exception(
                    f"Key '{key}' not found in JSON data", fail_test=False
                )
                return json_dict

            return nested_update(json_dict, key, updated_value)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error updating JSON based on key: {str(e)}", fail_test=False
            )
            return self.get_dict(json_data)

    def update_json_based_on_parent_child_key(
        self,
        json_data: Union[str, Dict[str, Any]],
        parent_key: str,
        child_key: str,
        updated_value: Any,
    ) -> Dict[str, Any]:
        """
        Update a specific child key within a parent key in the JSON data.

        Args:
            json_data: The JSON data (string or dictionary)
            parent_key: The parent key
            child_key: The child key to update
            updated_value: The new value for the child key

        Returns:
            The updated JSON dictionary
            The same JSON dictionary if parent_key or child_key is empty or doesn't exist

        Raises:
            ValueError: If json_data is invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"user": {"name": "John", "age": 30}}
            >>> updated = parser.update_json_based_on_parent_child_key(
            ...     data, "user", "name", "Jane"
            ... )
            >>> updated["user"]["name"]
            'Jane'
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return {}

            json_dict = self.get_dict(json_data)

            if not parent_key:
                self.exceptions.raise_generic_exception(
                    "parent_key cannot be null or empty", fail_test=False
                )
                return json_dict

            if not child_key:
                self.exceptions.raise_generic_exception(
                    "child_key cannot be null or empty", fail_test=False
                )
                return json_dict

            if not self.key_exists(json_dict, parent_key):
                self.exceptions.raise_generic_exception(
                    f"Parent key '{parent_key}' not found in JSON data", fail_test=False
                )
                return json_dict

            if not self.key_exists(json_dict, child_key):
                self.exceptions.raise_generic_exception(
                    f"Child key '{child_key}' not found in JSON data", fail_test=False
                )
                return json_dict

            # Combine parent and child keys using the special format for __parse_json_with_parent_key
            combined_key = f"{parent_key}->{child_key}"

            global bln_flag, bln_parent_key_status, bln_child_key_status, int_node_counter
            bln_flag = True
            bln_parent_key_status = False
            bln_child_key_status = False
            int_node_counter = 1

            return self.__parse_json_with_parent_key([combined_key], [updated_value], json_dict)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error updating JSON based on parent-child key: {str(e)}", fail_test=False
            )
            return self.get_dict(json_data)

    def update_json_based_on_parent_child_key_index(
        self,
        json_data: Union[str, Dict[str, Any]],
        parent_key: str,
        child_key: str,
        index: str,
        updated_value: Any,
    ) -> Dict[str, Any]:
        """
        Update a specific child key at a given index within a parent key in the JSON data.

        Args:
            json_data: The JSON data (string or dictionary)
            parent_key: The parent key
            child_key: The child key to update
            index: The index of the child key if multiple instances exist
            updated_value: The new value for the child key

        Returns:
            The updated JSON dictionary
            The same JSON dictionary if parent_key or child_key is empty or doesn't exist
            The same JSON dictionary if index is empty

        Raises:
            ValueError: If json_data is invalid

        Examples:
            >>> parser = ParseJsonData()
            >>> data = {"users": [{"name": "John"}, {"name": "Jane"}]}
            >>> updated = parser.update_json_based_on_parent_child_key_index(
            ...     data, "users", "name", "2", "Jane Doe"
            ... )
            >>> updated["users"][1]["name"]  # Index 2 points to the second element (0-indexed)
            'Jane Doe'
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception(
                    "json_data cannot be null or empty", fail_test=False
                )
                return {}

            json_dict = self.get_dict(json_data)

            if not parent_key:
                self.exceptions.raise_generic_exception(
                    "parent_key cannot be null or empty", fail_test=False
                )
                return json_dict

            if not child_key:
                self.exceptions.raise_generic_exception(
                    "child_key cannot be null or empty", fail_test=False
                )
                return json_dict

            if not index:
                self.exceptions.raise_generic_exception(
                    "index cannot be null or empty", fail_test=False
                )
                return json_dict

            if not self.key_exists(json_dict, parent_key):
                self.exceptions.raise_generic_exception(
                    f"Parent key '{parent_key}' not found in JSON data", fail_test=False
                )
                return json_dict

            if not self.key_exists(json_dict, child_key):
                self.exceptions.raise_generic_exception(
                    f"Child key '{child_key}' not found in JSON data", fail_test=False
                )
                return json_dict

            # Combine parent, child keys, and index using the special format for __parse_json_with_parent_key
            combined_key = f"{parent_key}->{child_key}${index}"

            global bln_flag, bln_parent_key_status, bln_child_key_status, int_node_counter
            bln_flag = True
            bln_parent_key_status = False
            bln_child_key_status = False
            int_node_counter = 1

            return self.__parse_json_with_parent_key([combined_key], [updated_value], json_dict)

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error updating JSON based on parent-child key with index: {str(e)}",
                fail_test=False,
            )
            return self.get_dict(json_data)

    def __update_portion_json(self, json_data: Any, key: str, value: Any) -> Any:
        """
        Update a portion of the JSON data based on the specified key and value.

        Args:
            json_data: The JSON data to update
            key: The key to update, possibly with an index
            value: The new value for the key

        Returns:
            The updated JSON data

        Note:
            This is an internal helper method used by update_json_based_on_parent_child_key
            and update_json_based_on_parent_child_key_index.
        """
        try:
            if not json_data:
                self.exceptions.raise_generic_exception("json_data cannot be null", fail_test=False)
                return json_data

            if not key:
                self.exceptions.raise_generic_exception("key cannot be null", fail_test=False)
                return json_data

            global bln_child_key_status, int_node_counter

            # Split the key if it contains an index
            key_parts = key.split("$")
            target_key = key_parts[0]
            target_index = int(key_parts[1]) if len(key_parts) > 1 else None

            if isinstance(json_data, dict):
                for json_key, json_value in json_data.items():
                    if target_key == json_key:
                        if target_index is not None and int_node_counter == target_index:
                            # Update value at the specified index
                            json_data[json_key] = value
                            bln_child_key_status = True
                        elif target_index is None:
                            # Update all occurrences if no index is specified
                            json_data[json_key] = value
                            bln_child_key_status = True

                        int_node_counter += 1
                    elif isinstance(json_value, (dict, list)):
                        # Recursively update nested structures
                        self.__update_portion_json(json_value, key, value)
            elif isinstance(json_data, list):
                for item in json_data:
                    if isinstance(item, (dict, list)):
                        # Recursively update items in the list
                        self.__update_portion_json(item, key, value)

            return json_data

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in __update_portion_json: {str(e)}", fail_test=False
            )
            return json_data

    def __parse_update_json(self, json_data: Any, keys: List[str], value: Any) -> Any:
        """
        Parse and update the JSON data based on the specified keys and value.

        Args:
            json_data: The JSON data to update
            keys: The list of keys representing the path to the target key
            value: The new value for the target key

        Returns:
            The updated JSON data

        Note:
            This is an internal helper method used by __parse_json_with_parent_key.
        """
        try:
            global int_keys_counter, bln_flag, bln_parent_key_status

            if bln_flag:
                if isinstance(json_data, dict):
                    for json_key, json_value in json_data.items():
                        if keys[int_keys_counter - 1] == json_key:
                            # Found the parent key, now look for the child key
                            self.__update_portion_json(json_value, keys[int_keys_counter], value)
                            bln_parent_key_status = True
                            bln_flag = False
                            break
                        if isinstance(json_value, (dict, list)):
                            # Recursively search for the parent key
                            self.__parse_update_json(json_value, keys, value)
                elif isinstance(json_data, list):
                    for item in json_data:
                        if isinstance(item, (dict, list)):
                            # Recursively search for the parent key in list items
                            self.__parse_update_json(item, keys, value)

            return json_data

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in __parse_update_json: {str(e)}", fail_test=False
            )
            return json_data

    def __parse_json_with_parent_key(
        self, keys: List[str], values: List[Any], json_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """
        Parse and update the JSON data based on the specified parent-child keys and values.

        Args:
            keys: The list of parent-child keys
            values: The list of new values corresponding to the keys
            json_data: The JSON data to update

        Returns:
            The updated JSON data

        Note:
            This is an internal helper method used by update_json_based_on_parent_child_key
            and update_json_based_on_parent_child_key_index.
        """
        try:
            if len(keys) != len(values):
                self.exceptions.raise_generic_exception(
                    "Number of keys and values must be the same", fail_test=False
                )
                return json_data

            global bln_flag, bln_parent_key_status, bln_child_key_status, int_node_counter, int_keys_counter

            for i, key in enumerate(keys):
                # Split the key into parent and child parts
                key_parts = key.split("->")

                bln_flag = True
                bln_parent_key_status = False
                bln_child_key_status = False
                int_node_counter = 1
                int_keys_counter = 1

                # Update the JSON data with the current key-value pair
                json_data = self.__parse_update_json(json_data, key_parts, values[i])

                if not bln_parent_key_status or not bln_child_key_status:
                    self.exceptions.raise_generic_exception(
                        f"Key '{key}' not found in JSON data", fail_test=False
                    )
                    return json_data

            return json_data

        except Exception as e:
            self.exceptions.raise_generic_exception(
                f"Error in __parse_json_with_parent_key: {str(e)}", fail_test=False
            )
            return json_data

__parse_json_with_parent_key(keys, values, json_data)

Parse and update the JSON data based on the specified parent-child keys and values.

Parameters:

Name Type Description Default
keys List[str]

The list of parent-child keys

required
values List[Any]

The list of new values corresponding to the keys

required
json_data Dict[str, Any]

The JSON data to update

required

Returns:

Type Description
Dict[str, Any]

The updated JSON data

Note

This is an internal helper method used by update_json_based_on_parent_child_key and update_json_based_on_parent_child_key_index.

Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
def __parse_json_with_parent_key(
    self, keys: List[str], values: List[Any], json_data: Dict[str, Any]
) -> Dict[str, Any]:
    """
    Parse and update the JSON data based on the specified parent-child keys and values.

    Args:
        keys: The list of parent-child keys
        values: The list of new values corresponding to the keys
        json_data: The JSON data to update

    Returns:
        The updated JSON data

    Note:
        This is an internal helper method used by update_json_based_on_parent_child_key
        and update_json_based_on_parent_child_key_index.
    """
    try:
        if len(keys) != len(values):
            self.exceptions.raise_generic_exception(
                "Number of keys and values must be the same", fail_test=False
            )
            return json_data

        global bln_flag, bln_parent_key_status, bln_child_key_status, int_node_counter, int_keys_counter

        for i, key in enumerate(keys):
            # Split the key into parent and child parts
            key_parts = key.split("->")

            bln_flag = True
            bln_parent_key_status = False
            bln_child_key_status = False
            int_node_counter = 1
            int_keys_counter = 1

            # Update the JSON data with the current key-value pair
            json_data = self.__parse_update_json(json_data, key_parts, values[i])

            if not bln_parent_key_status or not bln_child_key_status:
                self.exceptions.raise_generic_exception(
                    f"Key '{key}' not found in JSON data", fail_test=False
                )
                return json_data

        return json_data

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in __parse_json_with_parent_key: {str(e)}", fail_test=False
        )
        return json_data

__parse_update_json(json_data, keys, value)

Parse and update the JSON data based on the specified keys and value.

Parameters:

Name Type Description Default
json_data Any

The JSON data to update

required
keys List[str]

The list of keys representing the path to the target key

required
value Any

The new value for the target key

required

Returns:

Type Description
Any

The updated JSON data

Note

This is an internal helper method used by __parse_json_with_parent_key.

Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
def __parse_update_json(self, json_data: Any, keys: List[str], value: Any) -> Any:
    """
    Parse and update the JSON data based on the specified keys and value.

    Args:
        json_data: The JSON data to update
        keys: The list of keys representing the path to the target key
        value: The new value for the target key

    Returns:
        The updated JSON data

    Note:
        This is an internal helper method used by __parse_json_with_parent_key.
    """
    try:
        global int_keys_counter, bln_flag, bln_parent_key_status

        if bln_flag:
            if isinstance(json_data, dict):
                for json_key, json_value in json_data.items():
                    if keys[int_keys_counter - 1] == json_key:
                        # Found the parent key, now look for the child key
                        self.__update_portion_json(json_value, keys[int_keys_counter], value)
                        bln_parent_key_status = True
                        bln_flag = False
                        break
                    if isinstance(json_value, (dict, list)):
                        # Recursively search for the parent key
                        self.__parse_update_json(json_value, keys, value)
            elif isinstance(json_data, list):
                for item in json_data:
                    if isinstance(item, (dict, list)):
                        # Recursively search for the parent key in list items
                        self.__parse_update_json(item, keys, value)

        return json_data

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in __parse_update_json: {str(e)}", fail_test=False
        )
        return json_data

__update_portion_json(json_data, key, value)

Update a portion of the JSON data based on the specified key and value.

Parameters:

Name Type Description Default
json_data Any

The JSON data to update

required
key str

The key to update, possibly with an index

required
value Any

The new value for the key

required

Returns:

Type Description
Any

The updated JSON data

Note

This is an internal helper method used by update_json_based_on_parent_child_key and update_json_based_on_parent_child_key_index.

Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def __update_portion_json(self, json_data: Any, key: str, value: Any) -> Any:
    """
    Update a portion of the JSON data based on the specified key and value.

    Args:
        json_data: The JSON data to update
        key: The key to update, possibly with an index
        value: The new value for the key

    Returns:
        The updated JSON data

    Note:
        This is an internal helper method used by update_json_based_on_parent_child_key
        and update_json_based_on_parent_child_key_index.
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception("json_data cannot be null", fail_test=False)
            return json_data

        if not key:
            self.exceptions.raise_generic_exception("key cannot be null", fail_test=False)
            return json_data

        global bln_child_key_status, int_node_counter

        # Split the key if it contains an index
        key_parts = key.split("$")
        target_key = key_parts[0]
        target_index = int(key_parts[1]) if len(key_parts) > 1 else None

        if isinstance(json_data, dict):
            for json_key, json_value in json_data.items():
                if target_key == json_key:
                    if target_index is not None and int_node_counter == target_index:
                        # Update value at the specified index
                        json_data[json_key] = value
                        bln_child_key_status = True
                    elif target_index is None:
                        # Update all occurrences if no index is specified
                        json_data[json_key] = value
                        bln_child_key_status = True

                    int_node_counter += 1
                elif isinstance(json_value, (dict, list)):
                    # Recursively update nested structures
                    self.__update_portion_json(json_value, key, value)
        elif isinstance(json_data, list):
            for item in json_data:
                if isinstance(item, (dict, list)):
                    # Recursively update items in the list
                    self.__update_portion_json(item, key, value)

        return json_data

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in __update_portion_json: {str(e)}", fail_test=False
        )
        return json_data

compare_json(expected_json, actual_json, ignore_keys=None, ignore_extra=False)

Compare two JSON structures (strings or dictionaries).

Parameters:

Name Type Description Default
expected_json Union[str, Dict[str, Any]]

The expected JSON data (string or dictionary)

required
actual_json Union[str, Dict[str, Any]]

The actual JSON data (string or dictionary)

required
ignore_keys Optional[List[str]]

A list of keys to ignore during comparison

None
ignore_extra bool

Whether to ignore extra keys in actual_json

False

Returns:

Type Description
Union[bool, Tuple[bool, List[str]]]

True if the JSON structures are equal (considering ignore_keys and ignore_extra),

Union[bool, Tuple[bool, List[str]]]

otherwise a tuple containing False and a list of mismatches

Raises:

Type Description
ValueError

If the input JSON data is invalid

Examples:

>>> parser = ParseJsonData()
>>> parser.compare_json(
...     {"name": "John", "age": 30},
...     {"name": "John", "age": 30, "role": "admin"},
...     ignore_extra=True
... )
True
>>> result = parser.compare_json(
...     {"name": "John", "age": 30},
...     {"name": "John", "age": 25}
... )
>>> isinstance(result, tuple) and not result[0]
True
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def compare_json(
    self,
    expected_json: Union[str, Dict[str, Any]],
    actual_json: Union[str, Dict[str, Any]],
    ignore_keys: Optional[List[str]] = None,
    ignore_extra: bool = False,
) -> Union[bool, Tuple[bool, List[str]]]:
    """
    Compare two JSON structures (strings or dictionaries).

    Args:
        expected_json: The expected JSON data (string or dictionary)
        actual_json: The actual JSON data (string or dictionary)
        ignore_keys: A list of keys to ignore during comparison
        ignore_extra: Whether to ignore extra keys in actual_json

    Returns:
        True if the JSON structures are equal (considering ignore_keys and ignore_extra),
        otherwise a tuple containing False and a list of mismatches

    Raises:
        ValueError: If the input JSON data is invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> parser.compare_json(
        ...     {"name": "John", "age": 30},
        ...     {"name": "John", "age": 30, "role": "admin"},
        ...     ignore_extra=True
        ... )
        True
        >>> result = parser.compare_json(
        ...     {"name": "John", "age": 30},
        ...     {"name": "John", "age": 25}
        ... )
        >>> isinstance(result, tuple) and not result[0]
        True
    """

    try:
        if ignore_keys is None:
            ignore_keys = []

        if expected_json is None:
            self.exceptions.raise_generic_exception(
                "expected_json can not be None", fail_test=False
            )
            return False, ["expected_json can not be None"]

        if actual_json is None:
            self.exceptions.raise_generic_exception(
                "actual_json can not be None", fail_test=False
            )
            return False, ["actual_json can not be None"]

        if not isinstance(ignore_keys, list):
            self.exceptions.raise_generic_exception(
                "ignore_keys must be a list", fail_test=False
            )
            return False, ["ignore_keys must be a list"]

        if not isinstance(ignore_extra, bool):
            self.exceptions.raise_generic_exception(
                "ignore_extra must be a boolean", fail_test=False
            )
            return False, ["ignore_extra must be a boolean"]

        expected_dict = self.get_dict(expected_json)
        actual_dict = self.get_dict(actual_json)

        error_list = []

        def compare_dicts(
            expected: Dict[str, Any], actual: Dict[str, Any], path: str = ""
        ) -> None:
            for key, expected_value in expected.items():
                if key in ignore_keys:
                    continue

                if key not in actual:
                    error_list.append(f"Key '{path}{key}' does not exist in actual JSON")
                    continue

                actual_value = actual[key]

                if isinstance(expected_value, dict) and isinstance(actual_value, dict):
                    compare_dicts(expected_value, actual_value, f"{path}{key}.")
                elif isinstance(expected_value, list) and isinstance(actual_value, list):
                    if len(expected_value) != len(actual_value):
                        error_list.append(
                            f"List length mismatch for '{path}{key}': "
                            f"expected {len(expected_value)}, got {len(actual_value)}"
                        )
                    else:
                        for i, (exp_item, act_item) in enumerate(
                            zip(expected_value, actual_value)
                        ):
                            if isinstance(exp_item, dict) and isinstance(act_item, dict):
                                compare_dicts(exp_item, act_item, f"{path}{key}[{i}].")
                            elif exp_item != act_item:
                                error_list.append(
                                    f"Value mismatch at '{path}{key}[{i}]': "
                                    f"expected {exp_item}, got {act_item}"
                                )
                elif expected_value != actual_value:
                    error_list.append(
                        f"Value mismatch for '{path}{key}': "
                        f"expected {expected_value}, got {actual_value}"
                    )

            if not ignore_extra:
                for key in set(actual.keys()) - set(expected.keys()):
                    if key not in ignore_keys:
                        error_list.append(f"Unexpected key in actual JSON: '{path}{key}'")

        compare_dicts(expected_dict, actual_dict)

        if error_list:
            return False, error_list

        return True

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error comparing JSON objects: {str(e)}", fail_test=False
        )
        return False, [f"Error comparing JSON objects: {str(e)}"]

convert_json_to_xml(json_data)

Convert a JSON string/dict to an XML string.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON string/dict to convert

required

Returns:

Type Description
str

The XML string

Raises:

Type Description
ValueError

If the input JSON is invalid

Examples:

>>> parser = ParseJsonData()
>>> xml = parser.convert_json_to_xml({"name": "John", "age": 30})
>>> "<name>John</name>" in xml and "<age>30</age>" in xml
True
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def convert_json_to_xml(self, json_data: Union[str, Dict[str, Any]]) -> str:
    """
    Convert a JSON string/dict to an XML string.

    Args:
        json_data: The JSON string/dict to convert

    Returns:
        The XML string

    Raises:
        ValueError: If the input JSON is invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> xml = parser.convert_json_to_xml({"name": "John", "age": 30})
        >>> "<name>John</name>" in xml and "<age>30</age>" in xml
        True
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return ""

        json_dict = self.get_dict(json_data)
        xml_str = dicttoxml.dicttoxml(json_dict, custom_root="all", attr_type=False)
        return xml_str.decode()

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error converting JSON to XML: {str(e)}", fail_test=False
        )
        return ""

get_all_keys(json_data)

Extract all keys from a nested JSON dictionary as a list.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required

Returns:

Type Description
List[str]

A list of all keys found in the JSON data

Raises:

Type Description
ValueError

If the input JSON data is invalid

Examples:

>>> parser = ParseJsonData()
>>> keys = parser.get_all_keys({"user": {"name": "John", "age": 30}})
>>> sorted(keys)
['age', 'name', 'user']
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
def get_all_keys(self, json_data: Union[str, Dict[str, Any]]) -> List[str]:
    """
    Extract all keys from a nested JSON dictionary as a list.

    Args:
        json_data: The JSON data (string or dictionary)

    Returns:
        A list of all keys found in the JSON data

    Raises:
        ValueError: If the input JSON data is invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> keys = parser.get_all_keys({"user": {"name": "John", "age": 30}})
        >>> sorted(keys)
        ['age', 'name', 'user']
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return []

        json_dict = self.get_dict(json_data)
        return get_all_keys(json_dict)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error getting all keys: {str(e)}", fail_test=False
        )
        return []

get_dict(json_data)

Ensure the input is a valid JSON dictionary.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The input data, which can be either a JSON string or a dictionary

required

Returns:

Type Description
Dict[str, Any]

The parsed JSON dictionary

Raises:

Type Description
ValueError

If the input data is not a valid JSON string or dictionary

Examples:

>>> parser = ParseJsonData()
>>> parser.get_dict('{"name": "John"}')
{'name': 'John'}
>>> parser.get_dict({"name": "John"})
{'name': 'John'}
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def get_dict(self, json_data: Union[str, Dict[str, Any]]) -> Dict[str, Any]:
    """
    Ensure the input is a valid JSON dictionary.

    Args:
        json_data: The input data, which can be either a JSON string or a dictionary

    Returns:
        The parsed JSON dictionary

    Raises:
        ValueError: If the input data is not a valid JSON string or dictionary

    Examples:
        >>> parser = ParseJsonData()
        >>> parser.get_dict('{"name": "John"}')
        {'name': 'John'}
        >>> parser.get_dict({"name": "John"})
        {'name': 'John'}
    """
    try:
        if isinstance(json_data, dict):
            return json_data

        if isinstance(json_data, str):
            return json.loads(json_data)

        self.exceptions.raise_generic_exception(
            "Input must be a JSON string or dictionary", fail_test=False
        )
        return {}

    except json.JSONDecodeError as e:
        self.exceptions.raise_generic_exception(f"Invalid JSON data: {str(e)}", fail_test=False)
        return {}
    except Exception as e:
        self.exceptions.raise_generic_exception(f"Error in get_dict: {str(e)}", fail_test=False)
        return {}

get_json_result(json_data, key=None, nested=False, keypath=None, keypath_type=None, key_input=None, delimiter='/')

Get a value from JSON data based on key or key path.

This method is a convenience wrapper that provides a unified interface to retrieve values using either simple keys or complex key paths.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
key Optional[str]

The key to retrieve the value for (for simple key lookups)

None
nested bool

Whether to search for the key in nested structures (when using key)

False
keypath Optional[str]

The path to the key, using the specified delimiter (for path-based lookups)

None
keypath_type Optional[str]

Either "absolute" or "relative" (required when using keypath)

None
key_input Optional[str]

The specific sub-child key to retrieve the value for (when using relative keypath)

None
delimiter str

The delimiter used in the key path (default: "/")

'/'

Returns:

Type Description
Any

The value associated with the key or key path

Raises:

Type Description
ValueError

If required parameters are missing or invalid

Examples:

>>> parser = ParseJsonData()
>>> data = {"user": {"profile": {"name": "John"}}}
>>> # Simple key lookup
>>> parser.get_json_result(data, key="user")
{'profile': {'name': 'John'}}
>>> # Nested key lookup
>>> parser.get_json_result(data, key="name", nested=True)
['John']
>>> # Absolute key path lookup
>>> parser.get_json_result(
...     data,
...     keypath="user/profile/name",
...     keypath_type="absolute"
... )
'John'
>>> # Relative key path lookup
>>> parser.get_json_result(
...     data,
...     keypath="user/profile",
...     keypath_type="relative",
...     key_input="name"
... )
'John'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def get_json_result(
    self,
    json_data: Union[str, Dict[str, Any]],
    key: Optional[str] = None,
    nested: bool = False,
    keypath: Optional[str] = None,
    keypath_type: Optional[str] = None,
    key_input: Optional[str] = None,
    delimiter: str = "/",
) -> Any:
    """
    Get a value from JSON data based on key or key path.

    This method is a convenience wrapper that provides a unified interface to retrieve
    values using either simple keys or complex key paths.

    Args:
        json_data: The JSON data (string or dictionary)
        key: The key to retrieve the value for (for simple key lookups)
        nested: Whether to search for the key in nested structures (when using key)
        keypath: The path to the key, using the specified delimiter (for path-based lookups)
        keypath_type: Either "absolute" or "relative" (required when using keypath)
        key_input: The specific sub-child key to retrieve the value for (when using relative keypath)
        delimiter: The delimiter used in the key path (default: "/")

    Returns:
        The value associated with the key or key path

    Raises:
        ValueError: If required parameters are missing or invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"user": {"profile": {"name": "John"}}}
        >>> # Simple key lookup
        >>> parser.get_json_result(data, key="user")
        {'profile': {'name': 'John'}}
        >>> # Nested key lookup
        >>> parser.get_json_result(data, key="name", nested=True)
        ['John']
        >>> # Absolute key path lookup
        >>> parser.get_json_result(
        ...     data,
        ...     keypath="user/profile/name",
        ...     keypath_type="absolute"
        ... )
        'John'
        >>> # Relative key path lookup
        >>> parser.get_json_result(
        ...     data,
        ...     keypath="user/profile",
        ...     keypath_type="relative",
        ...     key_input="name"
        ... )
        'John'
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return None

        # Simple key lookup
        if key is not None:
            return self.get_value_of_key(json_data, key, nested)

        # Key path lookup
        if keypath is not None:
            if not keypath_type:
                self.exceptions.raise_generic_exception(
                    "keypath_type is required when using keypath", fail_test=False
                )
                return None

            return self.get_value_from_key_path(
                json_data=json_data,
                key_path=keypath,
                key_path_type=keypath_type,
                key=key_input,
                delimiter=delimiter,
            )

        self.exceptions.raise_generic_exception(
            "Either key or keypath must be provided", fail_test=False
        )
        return None

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in get_json_result: {str(e)}", fail_test=False
        )
        return None

get_json_values_by_key_path(json_data, delimiter='/', keypath=None, key=None, parser=False)

Extracts values from a JSON dictionary using a key path.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
delimiter str

The delimiter used in the key path

'/'
keypath Optional[str]

The key path to extract values from

None
key Optional[str]

The specific sub-child key to retrieve the value for

None
parser bool

If True, parses the json_data as a JSON string before processing

False

Returns:

Name Type Description
Any Any

The value(s) associated with the key path.

Raises:

Type Description
ValueError

If json_data or keypath is null or empty, or if key is not found

Examples:

>>> json_parser = ParseJsonData()
>>> data = {"users": {"admin": {"name": "Admin", "role": "admin"}}}
>>> json_parser.get_json_values_by_key_path(data, keypath="users/admin", key="name")
'Admin'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def get_json_values_by_key_path(
    self,
    json_data: Union[str, Dict[str, Any]],
    delimiter: str = "/",
    keypath: Optional[str] = None,
    key: Optional[str] = None,
    parser: bool = False,
) -> Any:
    """
    Extracts values from a JSON dictionary using a key path.

    Args:
        json_data: The JSON data (string or dictionary)
        delimiter: The delimiter used in the key path
        keypath: The key path to extract values from
        key: The specific sub-child key to retrieve the value for
        parser: If True, parses the json_data as a JSON string before processing

    Returns:
        Any: The value(s) associated with the key path.

    Raises:
        ValueError: If json_data or keypath is null or empty, or if key is not found
        in the nested dictionary

    Examples:
        >>> json_parser = ParseJsonData()
        >>> data = {"users": {"admin": {"name": "Admin", "role": "admin"}}}
        >>> json_parser.get_json_values_by_key_path(data, keypath="users/admin", key="name")
        'Admin'
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception("json_data cannot be null", fail_test=False)
            return None

        json_dict = self.get_dict(json_data)

        if parser:
            if not keypath:
                self.exceptions.raise_generic_exception(
                    "keypath cannot be null when parser is True", fail_test=False
                )
                return None

            modified_keypath = keypath.replace("/", ".") if delimiter == "/" else keypath
            json_tree = objectpath.Tree(json_dict)
            return json_tree.execute("$." + modified_keypath)

        if keypath:
            root_parent = keypath.split(delimiter)

            if len(root_parent) == 1:
                root = root_parent[0]
                if root not in json_dict:
                    self.exceptions.raise_generic_exception(
                        f"Key '{root}' not found in JSON data", fail_test=False
                    )
                    return None

                result = json_dict[root]
                # If we're looking for a specific subkey within this result
                if key is not None and isinstance(result, dict):
                    return result.get(key)
                return result

            root = root_parent[0]
            parent = root_parent[1]

            if root not in json_dict:
                self.exceptions.raise_generic_exception(
                    f"Root key '{root}' not found in JSON data", fail_test=False
                )
                return None

            json_tree = objectpath.Tree(json_dict[root])
            result_list = list(json_tree.execute("$.." + parent))

            for result in result_list:
                if key is not None and isinstance(result, dict):
                    return result.get(key)
                return result

        self.exceptions.raise_generic_exception(
            "Invalid arguments for get_json_values_by_key_path", fail_test=False
        )
        return None

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in get_json_values_by_key_path: {str(e)}", fail_test=False
        )
    return None

get_multiple_key_value(json_data, keys, key_paths=None, delimiter='/')

Get values for multiple keys and key paths from the JSON data.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
keys List[str]

List of keys for which to fetch values

required
key_paths Optional[List[str]]

Optional list of key paths for which to fetch values

None
delimiter str

The delimiter used in the key paths

'/'

Returns:

Type Description
Dict[str, Any]

A dictionary mapping keys and key paths to their values

Raises:

Type Description
ValueError

If json_data or keys is null or keys is not a list

Examples:

>>> parser = ParseJsonData()
>>> data = {"user": {"profile": {"name": "John", "age": 30}}}
>>> results = parser.get_multiple_key_value(
...     data, ["user"], key_paths=["user/profile", "user/profile/name"]
... )
>>> "user" in results and "user/profile" in results and "user/profile/name" in results
True
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def get_multiple_key_value(
    self,
    json_data: Union[str, Dict[str, Any]],
    keys: List[str],
    key_paths: Optional[List[str]] = None,
    delimiter: str = "/",
) -> Dict[str, Any]:
    """
    Get values for multiple keys and key paths from the JSON data.

    Args:
        json_data: The JSON data (string or dictionary)
        keys: List of keys for which to fetch values
        key_paths: Optional list of key paths for which to fetch values
        delimiter: The delimiter used in the key paths

    Returns:
        A dictionary mapping keys and key paths to their values

    Raises:
        ValueError: If json_data or keys is null or keys is not a list

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"user": {"profile": {"name": "John", "age": 30}}}
        >>> results = parser.get_multiple_key_value(
        ...     data, ["user"], key_paths=["user/profile", "user/profile/name"]
        ... )
        >>> "user" in results and "user/profile" in results and "user/profile/name" in results
        True
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return {}

        if not keys:
            self.exceptions.raise_generic_exception(
                "keys cannot be null or empty", fail_test=False
            )
            return {}

        if not isinstance(keys, list):
            self.exceptions.raise_generic_exception("keys must be a list", fail_test=False)
            return {}

        result = {}
        json_dict = self.get_dict(json_data)

        # Get values for keys
        for key in keys:
            result[key] = nested_lookup(key, json_dict)

        # Get values for key paths
        if key_paths:
            for key_path in key_paths:
                try:
                    result[key_path] = self.get_value_of_key_path(
                        json_dict, key_path, delimiter
                    )
                except Exception as e:
                    self.logger.warning(
                        "Error getting value for key path '%s': %s", key_path, str(e)
                    )
                    result[key_path] = None

        return result

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error getting multiple key values: {str(e)}", fail_test=False
        )
        return {}

get_occurrence_of_key(json_data, key)

Count the occurrences of a key in the JSON data.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
key str

The key to count occurrences of

required

Returns:

Type Description
int

The number of occurrences of the key

Raises:

Type Description
ValueError

If the input JSON data is invalid or the key is empty

Examples:

>>> parser = ParseJsonData()
>>> data = {"name": "John", "address": {"name": "Home", "street": "Main St"}}
>>> parser.get_occurrence_of_key(data, "name")
2
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
def get_occurrence_of_key(self, json_data: Union[str, Dict[str, Any]], key: str) -> int:
    """
    Count the occurrences of a key in the JSON data.

    Args:
        json_data: The JSON data (string or dictionary)
        key: The key to count occurrences of

    Returns:
        The number of occurrences of the key

    Raises:
        ValueError: If the input JSON data is invalid or the key is empty

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"name": "John", "address": {"name": "Home", "street": "Main St"}}
        >>> parser.get_occurrence_of_key(data, "name")
        2
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return 0

        if not key:
            self.exceptions.raise_generic_exception(
                "key cannot be null or empty", fail_test=False
            )
            return 0

        json_dict = self.get_dict(json_data)
        return get_occurrence_of_key(json_dict, key)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error getting occurrence of key: {str(e)}", fail_test=False
        )
        return 0

get_value(json_dict, key)

Gets the value of a key from the first level of a JSON dictionary.

Parameters:

Name Type Description Default
json_dict dict

The JSON dictionary to search.

required
key str

The key to retrieve the value for.

required

Returns:

Type Description
Any

The value associated with the key, or None if not found.

Raises:

Type Description
ValueError

If json_dict is not a dictionary or the key is not found.

Examples:

>>> parser = ParseJsonData()
>>> data = {"name": "John", "age": 30}
>>> parser.get_value(data, "name")
'John'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def get_value(self, json_dict: Dict[str, Any], key: str) -> Any:
    """
    Gets the value of a key from the first level of a JSON dictionary.

    Args:
        json_dict (dict): The JSON dictionary to search.
        key (str): The key to retrieve the value for.

    Returns:
        The value associated with the key, or None if not found.

    Raises:
        ValueError: If json_dict is not a dictionary or the key is not found.

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"name": "John", "age": 30}
        >>> parser.get_value(data, "name")
        'John'
    """
    if not isinstance(json_dict, dict):
        self.exceptions.raise_generic_exception(
            "json_dict must be a dictionary", fail_test=False
        )
        return None

    if not key:
        self.exceptions.raise_generic_exception("key cannot be null or empty", fail_test=False)
        return None

    try:
        return json_dict[key]
    except KeyError:
        self.exceptions.raise_generic_exception(
            f"Key '{key}' not in the JSON dictionary", fail_test=False
        )
        return None

get_value_from_key_path(json_data, key_path, key_path_type, key=None, delimiter='/')

Extract the value at the specified key path from the JSON data.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
key_path str

The path to the key, using the specified delimiter

required
key_path_type str

Either "absolute" or "relative"

required
key Optional[str]

The key to retrieve the value for when using relative key paths

None
delimiter str

The delimiter used in the key path

'/'

Returns:

Type Description
Any

The value associated with the key path

Raises:

Type Description
ValueError

If required arguments are missing, invalid, or the key path is not found

Examples:

>>> parser = ParseJsonData()
>>> data = {"users": {"admin": {"name": "Admin", "role": "admin"}}}
>>> parser.get_value_from_key_path(
...     data, "users/admin", "absolute"
... )
{'name': 'Admin', 'role': 'admin'}
>>> parser.get_value_from_key_path(
...     data, "users/admin", "relative", "name"
... )
'Admin'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def get_value_from_key_path(
    self,
    json_data: Union[str, Dict[str, Any]],
    key_path: str,
    key_path_type: str,
    key: Optional[str] = None,
    delimiter: str = "/",
) -> Any:
    """
    Extract the value at the specified key path from the JSON data.

    Args:
        json_data: The JSON data (string or dictionary)
        key_path: The path to the key, using the specified delimiter
        key_path_type: Either "absolute" or "relative"
        key: The key to retrieve the value for when using relative key paths
        delimiter: The delimiter used in the key path

    Returns:
        The value associated with the key path

    Raises:
        ValueError: If required arguments are missing, invalid, or the key path is not found

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"users": {"admin": {"name": "Admin", "role": "admin"}}}
        >>> parser.get_value_from_key_path(
        ...     data, "users/admin", "absolute"
        ... )
        {'name': 'Admin', 'role': 'admin'}
        >>> parser.get_value_from_key_path(
        ...     data, "users/admin", "relative", "name"
        ... )
        'Admin'
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception("json_data cannot be null", fail_test=False)
            return None

        if not key_path:
            self.exceptions.raise_generic_exception("key_path cannot be null", fail_test=False)
            return None

        if not key_path_type:
            self.exceptions.raise_generic_exception(
                "key_path_type cannot be null", fail_test=False
            )
            return None

        json_dict = self.get_dict(json_data)

        key_path_type = key_path_type.lower()

        if key_path_type == "absolute":
            return self.get_value_of_key_path(json_dict, key_path, delimiter)
        if key_path_type == "relative":
            if key is None:
                self.exceptions.raise_generic_exception(
                    "key argument is required if key_path_type is relative", fail_test=False
                )
                return None

            return self.get_json_values_by_key_path(
                json_dict, delimiter, keypath=key_path, key=key
            )

        self.exceptions.raise_generic_exception(
            "Invalid key_path_type. Use 'absolute' or 'relative'", fail_test=False
        )
        return None

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in get_value_from_key_path: {str(e)}", fail_test=False
        )
        return None

get_value_of_key(json_data, key, nested=False)

Gets the value of a key from the JSON data, optionally searching nested structures.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data to parse (either a string or a dictionary).

required
key str

The key to retrieve the value for.

required
nested bool

Whether to search for the key in nested structures (default: False).

False

Returns:

Type Description
Any

The value associated with the key, or a list of values if nested is True and multiple keys are found.

Raises:

Type Description
ValueError

If json_data is not a dictionary or the key is not found.

Examples:

>>> parser = ParseJsonData()
>>> data = {"user": {"name": "John"}, "admin": {"name": "Admin"}}
>>> parser.get_value_of_key(data, "user", False)
{'name': 'John'}
>>> parser.get_value_of_key(data, "name", True)
['John', 'Admin']
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def get_value_of_key(
    self, json_data: Union[str, Dict[str, Any]], key: str, nested: bool = False
) -> Any:
    """
    Gets the value of a key from the JSON data, optionally searching nested structures.

    Args:
        json_data: The JSON data to parse (either a string or a dictionary).
        key: The key to retrieve the value for.
        nested: Whether to search for the key in nested structures (default: False).

    Returns:
        The value associated with the key, or a list of values if nested is True and multiple keys are found.

    Raises:
        ValueError: If json_data is not a dictionary or the key is not found.

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"user": {"name": "John"}, "admin": {"name": "Admin"}}
        >>> parser.get_value_of_key(data, "user", False)
        {'name': 'John'}
        >>> parser.get_value_of_key(data, "name", True)
        ['John', 'Admin']
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return None if not nested else []

        if not key:
            self.exceptions.raise_generic_exception(
                "key cannot be null or empty", fail_test=False
            )
            return None if not nested else []

        json_dict = self.get_dict(json_data)

        if nested:
            return nested_lookup(key, json_dict)

        return self.get_value(json_dict, key)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error getting value of key: {str(e)}", fail_test=False
        )
        return None if not nested else []

get_value_of_key_path(json_dict, key_path, delimiter='/')

Gets the value of a key from a nested JSON dictionary using the provided key path.

Parameters:

Name Type Description Default
json_dict dict

The JSON dictionary to search.

required
key_path str

The path to the key, using the specified delimiter.

required
delimiter str

The delimiter used in the key path (default: "/").

'/'

Returns:

Name Type Description
Any Any

The value associated with the key path, or None if not found.

Raises:

Type Description
ValueError

If json_dict is not a dictionary or the key path is not found.

Examples:

>>> parser = ParseJsonData()
>>> data = {"user": {"profile": {"name": "John"}}}
>>> parser.get_value_of_key_path(data, "user/profile/name")
'John'
>>> parser.get_value_of_key_path(data, "user.profile.name", ".")
'John'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def get_value_of_key_path(
    self, json_dict: Dict[str, Any], key_path: str, delimiter: str = "/"
) -> Any:
    """
    Gets the value of a key from a nested JSON dictionary using the provided key path.

    Args:
        json_dict (dict): The JSON dictionary to search.
        key_path (str): The path to the key, using the specified delimiter.
        delimiter (str, optional): The delimiter used in the key path (default: "/").

    Returns:
        Any: The value associated with the key path, or None if not found.

    Raises:
        ValueError: If json_dict is not a dictionary or the key path is not found.

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"user": {"profile": {"name": "John"}}}
        >>> parser.get_value_of_key_path(data, "user/profile/name")
        'John'
        >>> parser.get_value_of_key_path(data, "user.profile.name", ".")
        'John'
    """
    try:
        if not isinstance(json_dict, dict):
            self.exceptions.raise_generic_exception(
                "json_dict must be a dictionary", fail_test=False
            )
            return None

        if not key_path:
            self.exceptions.raise_generic_exception(
                "key_path cannot be null or empty", fail_test=False
            )
            return None
        # Split the key path into segments
        key_list = key_path.split(delimiter)

        def get_item(obj, key):
            if isinstance(obj, list) and key.isdigit():
                # Convert string index to integer for list access
                return obj[int(key)]
            return obj[key]

        return reduce(get_item, key_list, json_dict)
    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in fetching key value using the provided key path: {str(e)}",
            fail_test=False,
        )
        return None

is_json(json_data)

Check if the input is a valid JSON string and return the parsed dictionary.

Parameters:

Name Type Description Default
json_data str

The input data to be checked

required

Returns:

Type Description
Dict[str, Any]

The parsed JSON dictionary if json_data is valid JSON

Raises:

Type Description
ValueError

If the input data is not valid JSON

Examples:

>>> parser = ParseJsonData()
>>> parser.is_json('{"name": "John"}')
{'name': 'John'}
>>> parser.is_json('invalid')
Traceback (most recent call last):
...
ValueError: Invalid JSON data: ...
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def is_json(self, json_data: str) -> Dict[str, Any]:
    """
    Check if the input is a valid JSON string and return the parsed dictionary.

    Args:
        json_data: The input data to be checked

    Returns:
        The parsed JSON dictionary if json_data is valid JSON

    Raises:
        ValueError: If the input data is not valid JSON

    Examples:
        >>> parser = ParseJsonData()
        >>> parser.is_json('{"name": "John"}')
        {'name': 'John'}
        >>> parser.is_json('invalid')
        Traceback (most recent call last):
        ...
        ValueError: Invalid JSON data: ...
    """

    try:
        return json.loads(json_data)
    except json.JSONDecodeError as e:
        self.exceptions.raise_generic_exception(f"Invalid JSON data: {str(e)}", fail_test=False)
        return {}

key_exists(json_data, key)

Check if a key exists in the JSON data.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
key str

The key to check for

required

Returns:

Type Description
bool

True if the key exists, False otherwise

Raises:

Type Description
ValueError

If the input JSON data is invalid or the key is empty

Examples:

>>> parser = ParseJsonData()
>>> data = {"name": "John", "age": 30}
>>> parser.key_exists(data, "name")
True
>>> parser.key_exists(data, "email")
False
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
def key_exists(self, json_data: Union[str, Dict[str, Any]], key: str) -> bool:
    """
    Check if a key exists in the JSON data.

    Args:
        json_data: The JSON data (string or dictionary)
        key: The key to check for

    Returns:
        True if the key exists, False otherwise

    Raises:
        ValueError: If the input JSON data is invalid or the key is empty

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"name": "John", "age": 30}
        >>> parser.key_exists(data, "name")
        True
        >>> parser.key_exists(data, "email")
        False
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return False

        if not key:
            self.exceptions.raise_generic_exception(
                "key cannot be null or empty", fail_test=False
            )
            return False

        all_keys = self.get_all_keys(json_data)
        return key in all_keys

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error checking if key exists: {str(e)}", fail_test=False
        )
        return False

level_based_value(json_data, key, level=0)

Get values for a key at a specific level in a nested JSON structure.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
key str

The key to search for

required
level int

The level in the JSON hierarchy to search (0-based)

0

Returns:

Type Description
List[Any]

A list of values found for the key at the specified level

Raises:

Type Description
ValueError

If json_data or key is null or empty, or if level is not an integer

Examples:

>>> parser = ParseJsonData()
>>> data = {
...     "level0": "value0",
...     "nested": {
...         "level1": "value1",
...         "more": {
...             "level2": "value2"
...         }
...     }
... }
>>> parser.level_based_value(data, "level0", 0)
['value0']
>>> parser.level_based_value(data, "level1", 1)
['value1']
>>> parser.level_based_value(data, "level2", 2)
['value2']
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def level_based_value(
    self, json_data: Union[str, Dict[str, Any]], key: str, level: int = 0
) -> List[Any]:
    """
    Get values for a key at a specific level in a nested JSON structure.

    Args:
        json_data: The JSON data (string or dictionary)
        key: The key to search for
        level: The level in the JSON hierarchy to search (0-based)

    Returns:
        A list of values found for the key at the specified level

    Raises:
        ValueError: If json_data or key is null or empty, or if level is not an integer

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {
        ...     "level0": "value0",
        ...     "nested": {
        ...         "level1": "value1",
        ...         "more": {
        ...             "level2": "value2"
        ...         }
        ...     }
        ... }
        >>> parser.level_based_value(data, "level0", 0)
        ['value0']
        >>> parser.level_based_value(data, "level1", 1)
        ['value1']
        >>> parser.level_based_value(data, "level2", 2)
        ['value2']
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return []

        if not key:
            self.exceptions.raise_generic_exception(
                "key cannot be null or empty", fail_test=False
            )
            return []

        if not isinstance(level, int):
            self.exceptions.raise_generic_exception("level must be an integer", fail_test=False)
            return []

        json_dict = self.get_dict(json_data)

        def search_at_level(
            data: Any, search_key: str, current_level: int, target_level: int
        ) -> List[Any]:
            results = []

            if isinstance(data, dict):
                for k, v in data.items():
                    if k == search_key and current_level == target_level:
                        results.append(v)

                    if isinstance(v, (dict, list)) and current_level < target_level:
                        results.extend(
                            search_at_level(v, search_key, current_level + 1, target_level)
                        )
            elif isinstance(data, list):
                for item in data:
                    if isinstance(item, (dict, list)):
                        results.extend(
                            search_at_level(item, search_key, current_level, target_level)
                        )

            return results

        return search_at_level(json_dict, key, 0, level)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error in level_based_value: {str(e)}", fail_test=False
        )
        return []

print_all_key_values(json_data)

Print all key-value pairs in a nested dictionary structure.

Parameters:

Name Type Description Default
json_data Dict[str, Any]

The nested dictionary to print

required

Raises:

Type Description
ValueError

If json_data is not a dictionary

Examples:

>>> parser = ParseJsonData()
>>> data = {"user": {"name": "John", "age": 30}}
>>> parser.print_all_key_values(data)
user:
  name: John
  age: 30
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
def print_all_key_values(self, json_data: Dict[str, Any]) -> None:
    """
    Print all key-value pairs in a nested dictionary structure.

    Args:
        json_data: The nested dictionary to print

    Raises:
        ValueError: If json_data is not a dictionary

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"user": {"name": "John", "age": 30}}
        >>> parser.print_all_key_values(data)
        user:
          name: John
          age: 30
    """
    try:
        if not isinstance(json_data, dict):
            self.exceptions.raise_generic_exception(
                "json_data must be a dictionary", fail_test=False
            )
            return

        def _print_nested(data: Dict[str, Any], indent: int = 0) -> None:
            for key, value in data.items():
                if isinstance(value, dict):
                    self.logger.debug("%s%s:", " " * indent, key)
                    _print_nested(value, indent + 2)
                else:
                    self.logger.debug("%s%s: %s", " " * indent, key, value)

        _print_nested(json_data)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error while printing all key-value pairs: {str(e)}", fail_test=False
        )

read_json_file(file_path)

Reads a JSON file and returns the parsed dictionary.

Parameters:

Name Type Description Default
file_path str

The path to the JSON file.

required

Returns:

Type Description
Dict[str, Any]

The parsed JSON dictionary.

Raises:

Type Description
FileNotFoundError

If the JSON file is not found.

ValueError

If the JSON file contains invalid JSON.

Examples:

>>> parser = ParseJsonData()
>>> data = parser.read_json_file("config.json")
>>> print(data["version"])
'1.0'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def read_json_file(self, file_path: str) -> Dict[str, Any]:
    """
    Reads a JSON file and returns the parsed dictionary.

    Args:
        file_path: The path to the JSON file.

    Returns:
        The parsed JSON dictionary.

    Raises:
        FileNotFoundError: If the JSON file is not found.
        ValueError: If the JSON file contains invalid JSON.

    Examples:
        >>> parser = ParseJsonData()
        >>> data = parser.read_json_file("config.json")
        >>> print(data["version"])
        '1.0'
    """
    try:
        if not os.path.exists(file_path):
            self.exceptions.raise_generic_exception(
                f"JSON file not found: {file_path}", fail_test=False
            )
            return {}

        with open(file_path, "r", encoding="utf-8") as json_file:
            return json.load(json_file)
    except json.JSONDecodeError as e:
        self.exceptions.raise_generic_exception(
            f"Error parsing JSON file: {str(e)}", fail_test=False
        )
        return {}
    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error reading JSON file: {str(e)}", fail_test=False
        )
        return {}

update_json_based_on_key(json_data, key, updated_value)

Update all occurrences of a key in the JSON data with a new value.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
key str

The key to update

required
updated_value Any

The new value for the key

required

Returns:

Type Description
Dict[str, Any]

The updated JSON dictionary

Dict[str, Any]

The same JSON dictionary if key is empty or key doesn't exist in the JSON data

Raises:

Type Description
ValueError

If json_data is invalid

Examples:

>>> parser = ParseJsonData()
>>> data = {"name": "John", "user": {"name": "John"}}
>>> updated = parser.update_json_based_on_key(data, "name", "Jane")
>>> updated["name"] == "Jane" and updated["user"]["name"] == "Jane"
True
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
def update_json_based_on_key(
    self, json_data: Union[str, Dict[str, Any]], key: str, updated_value: Any
) -> Dict[str, Any]:
    """
    Update all occurrences of a key in the JSON data with a new value.

    Args:
        json_data: The JSON data (string or dictionary)
        key: The key to update
        updated_value: The new value for the key

    Returns:
        The updated JSON dictionary
        The same JSON dictionary if key is empty or key doesn't exist in the JSON data

    Raises:
        ValueError: If json_data is invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"name": "John", "user": {"name": "John"}}
        >>> updated = parser.update_json_based_on_key(data, "name", "Jane")
        >>> updated["name"] == "Jane" and updated["user"]["name"] == "Jane"
        True
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return {}

        json_dict = self.get_dict(json_data)

        if not key:
            self.exceptions.raise_generic_exception(
                "key cannot be null or empty", fail_test=False
            )
            return json_dict

        if not self.key_exists(json_dict, key):
            self.exceptions.raise_generic_exception(
                f"Key '{key}' not found in JSON data", fail_test=False
            )
            return json_dict

        return nested_update(json_dict, key, updated_value)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error updating JSON based on key: {str(e)}", fail_test=False
        )
        return self.get_dict(json_data)

update_json_based_on_parent_child_key(json_data, parent_key, child_key, updated_value)

Update a specific child key within a parent key in the JSON data.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
parent_key str

The parent key

required
child_key str

The child key to update

required
updated_value Any

The new value for the child key

required

Returns:

Type Description
Dict[str, Any]

The updated JSON dictionary

Dict[str, Any]

The same JSON dictionary if parent_key or child_key is empty or doesn't exist

Raises:

Type Description
ValueError

If json_data is invalid

Examples:

>>> parser = ParseJsonData()
>>> data = {"user": {"name": "John", "age": 30}}
>>> updated = parser.update_json_based_on_parent_child_key(
...     data, "user", "name", "Jane"
... )
>>> updated["user"]["name"]
'Jane'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
def update_json_based_on_parent_child_key(
    self,
    json_data: Union[str, Dict[str, Any]],
    parent_key: str,
    child_key: str,
    updated_value: Any,
) -> Dict[str, Any]:
    """
    Update a specific child key within a parent key in the JSON data.

    Args:
        json_data: The JSON data (string or dictionary)
        parent_key: The parent key
        child_key: The child key to update
        updated_value: The new value for the child key

    Returns:
        The updated JSON dictionary
        The same JSON dictionary if parent_key or child_key is empty or doesn't exist

    Raises:
        ValueError: If json_data is invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"user": {"name": "John", "age": 30}}
        >>> updated = parser.update_json_based_on_parent_child_key(
        ...     data, "user", "name", "Jane"
        ... )
        >>> updated["user"]["name"]
        'Jane'
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return {}

        json_dict = self.get_dict(json_data)

        if not parent_key:
            self.exceptions.raise_generic_exception(
                "parent_key cannot be null or empty", fail_test=False
            )
            return json_dict

        if not child_key:
            self.exceptions.raise_generic_exception(
                "child_key cannot be null or empty", fail_test=False
            )
            return json_dict

        if not self.key_exists(json_dict, parent_key):
            self.exceptions.raise_generic_exception(
                f"Parent key '{parent_key}' not found in JSON data", fail_test=False
            )
            return json_dict

        if not self.key_exists(json_dict, child_key):
            self.exceptions.raise_generic_exception(
                f"Child key '{child_key}' not found in JSON data", fail_test=False
            )
            return json_dict

        # Combine parent and child keys using the special format for __parse_json_with_parent_key
        combined_key = f"{parent_key}->{child_key}"

        global bln_flag, bln_parent_key_status, bln_child_key_status, int_node_counter
        bln_flag = True
        bln_parent_key_status = False
        bln_child_key_status = False
        int_node_counter = 1

        return self.__parse_json_with_parent_key([combined_key], [updated_value], json_dict)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error updating JSON based on parent-child key: {str(e)}", fail_test=False
        )
        return self.get_dict(json_data)

update_json_based_on_parent_child_key_index(json_data, parent_key, child_key, index, updated_value)

Update a specific child key at a given index within a parent key in the JSON data.

Parameters:

Name Type Description Default
json_data Union[str, Dict[str, Any]]

The JSON data (string or dictionary)

required
parent_key str

The parent key

required
child_key str

The child key to update

required
index str

The index of the child key if multiple instances exist

required
updated_value Any

The new value for the child key

required

Returns:

Type Description
Dict[str, Any]

The updated JSON dictionary

Dict[str, Any]

The same JSON dictionary if parent_key or child_key is empty or doesn't exist

Dict[str, Any]

The same JSON dictionary if index is empty

Raises:

Type Description
ValueError

If json_data is invalid

Examples:

>>> parser = ParseJsonData()
>>> data = {"users": [{"name": "John"}, {"name": "Jane"}]}
>>> updated = parser.update_json_based_on_parent_child_key_index(
...     data, "users", "name", "2", "Jane Doe"
... )
>>> updated["users"][1]["name"]  # Index 2 points to the second element (0-indexed)
'Jane Doe'
Source code in libs\cafex_core\src\cafex_core\parsers\json_parser.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
def update_json_based_on_parent_child_key_index(
    self,
    json_data: Union[str, Dict[str, Any]],
    parent_key: str,
    child_key: str,
    index: str,
    updated_value: Any,
) -> Dict[str, Any]:
    """
    Update a specific child key at a given index within a parent key in the JSON data.

    Args:
        json_data: The JSON data (string or dictionary)
        parent_key: The parent key
        child_key: The child key to update
        index: The index of the child key if multiple instances exist
        updated_value: The new value for the child key

    Returns:
        The updated JSON dictionary
        The same JSON dictionary if parent_key or child_key is empty or doesn't exist
        The same JSON dictionary if index is empty

    Raises:
        ValueError: If json_data is invalid

    Examples:
        >>> parser = ParseJsonData()
        >>> data = {"users": [{"name": "John"}, {"name": "Jane"}]}
        >>> updated = parser.update_json_based_on_parent_child_key_index(
        ...     data, "users", "name", "2", "Jane Doe"
        ... )
        >>> updated["users"][1]["name"]  # Index 2 points to the second element (0-indexed)
        'Jane Doe'
    """
    try:
        if not json_data:
            self.exceptions.raise_generic_exception(
                "json_data cannot be null or empty", fail_test=False
            )
            return {}

        json_dict = self.get_dict(json_data)

        if not parent_key:
            self.exceptions.raise_generic_exception(
                "parent_key cannot be null or empty", fail_test=False
            )
            return json_dict

        if not child_key:
            self.exceptions.raise_generic_exception(
                "child_key cannot be null or empty", fail_test=False
            )
            return json_dict

        if not index:
            self.exceptions.raise_generic_exception(
                "index cannot be null or empty", fail_test=False
            )
            return json_dict

        if not self.key_exists(json_dict, parent_key):
            self.exceptions.raise_generic_exception(
                f"Parent key '{parent_key}' not found in JSON data", fail_test=False
            )
            return json_dict

        if not self.key_exists(json_dict, child_key):
            self.exceptions.raise_generic_exception(
                f"Child key '{child_key}' not found in JSON data", fail_test=False
            )
            return json_dict

        # Combine parent, child keys, and index using the special format for __parse_json_with_parent_key
        combined_key = f"{parent_key}->{child_key}${index}"

        global bln_flag, bln_parent_key_status, bln_child_key_status, int_node_counter
        bln_flag = True
        bln_parent_key_status = False
        bln_child_key_status = False
        int_node_counter = 1

        return self.__parse_json_with_parent_key([combined_key], [updated_value], json_dict)

    except Exception as e:
        self.exceptions.raise_generic_exception(
            f"Error updating JSON based on parent-child key with index: {str(e)}",
            fail_test=False,
        )
        return self.get_dict(json_data)