What is the best way to decode and extract data from this JSON file using JavaScript or AngularJS?

I am encountering an issue while attempting to parse the following JSON. When trying to extract the value using the code below, it returns undefined.

Is there a method to successfully parse JSON where the keys contain spaces?

 {
        "Transport Fee":{
        "KARNATAKA":{
        "ALL_DISTRICT":{
        "ALL_PLACES":{
        "amount":4000
        }
        }
        },
        "ANDRA":{
        "ALL_DISTRICT":{
        "ALL_PLACES​":{
        "amount":100
        }
        }
        },
        "MP":{
        "ALL_DISTRICT":{
        "ALL_PLACES​":{
        "amount":600
        }
        }
        },
        "MAHARASHTRA":{
        "ALL_DISTRICT":{
        "ALL_PLACES​":{
        "amount":600
        }
        }
        }
        }
    }
      var promise=feeService.getTraspotaionFee();
        promise.then(function(data){
            $scope.charge=data;
            console.log($scope.charge.data["Transport Fee"]["KARNATAKA"]["ALL_DISTRICT"]["amount"]);

        });

Answer №1

It appears that your JSON is invalid due to a missing curly bracket at the end. I recommend using a JSON Validator to easily pinpoint and fix any issues with JSON data.

<-- This validator is quite helpful!

Answer №2

{
        "Transportation Fee":{
        "KARNATAKA":{
        "ALL_DISTRICT":{
        "ALL_PLACES":{
        "amount":4000
        }
        }
        },
        "ANDRA":{
        "ALL_DISTRICT":{
        "ALL_PLACES​":{
        "amount":100
        }
        }
        },
        "MP":{
        "ALL_DISTRICT":{
        "ALL_PLACES​":{
        "amount":600
        }
        }
        },
        "MAHARASHTRA":{
        "ALL_DISTRICT":{
        "ALL_PLACES​":{
        "amount":600
        }
        }
        }

      var promise=feeService.getTransportationFee();
        promise.then(function(data){
            $scope.charge=data;
            console.log($scope.charge.data["Transportation Fee"]["KARNATAKA"]["ALL_DISTRICT"]["ALL_PLACES"]["amount"]);

        });

Oops! The key should be "transportation fee" instead of "trasport fee". Don't forget to include ALL_PLACES before the amount.

Answer №3

My suggested correction would be:

console.log($scope.charge.data["Transport Fee"]["KARNATAKA"]["ALL_DISTRICT"]["ALL_PLACES"]["amount"]);
                                                                           ^^^^^^^^^^^^^^

I have also rectified your JSON by adding missing brackets:

{
   "Transport Fee":{
      "KARNATAKA":{
         "ALL_DISTRICT":{
            "ALL_PLACES":{
               "amount":4000
            }
         }
      },
      "ANDRA":{
         "ALL_DISTRICT":{
            "ALL_PLACES​":{
               "amount":100
            }
         }
      },
      "MP":{
         "ALL_DISTRICT":{
            "ALL_PLACES​":{
               "amount":600
            }
         }
      },
      "MAHARASHTRA":{
         "ALL_DISTRICT":{
            "ALL_PLACES​":{
               "amount":600
            }
         }
      }
   }
}

Answer №4

    var promise=feeService.fetchShippingCost();
        promise.then(function(info){
            $scope.fee=info;

//modified section
            console.log($scope.fee.data[Object.keys($scope.fee.data)[0]]["KARNATAKA"]["ALL_DISTRICT"]["ALL_PLACES"]["cost"]);

        });

Revise the code snippet above and implement

Answer №5

observation :

  • It is not a problem with the spaces in the key. The value is being accessed correctly.

  • The reason why you are getting undefined is because you are trying to access the amount property inside the ALL_DISTRICT object which does not exist.

Consider this:

$scope.charge.data["Trasport Fee"]["KARNATAKA"]["ALL_DISTRICT"]["ALL_PLACES"]["amount"]

DEMO

var data = {
"Trasport Fee": {
"KARNATAKA": {
"ALL_DISTRICT": {
"ALL_PLACES": {
"amount": 4000
}
}
},
"ANDRA": {
"ALL_DISTRICT": {
"ALL_PLACES": {
"amount": 100
}
}
},
"MP": {
"ALL_DISTRICT": {
"ALL_PLACES": {
"amount": 600
}
}
},
"MAHARASHTRA": {
"ALL_DISTRICT": {
"ALL_PLACES": {
"amount": 600
}
}
}
}
};

console.log(data["Trasport Fee"]["KARNATAKA"]["ALL_DISTRICT"]["ALL_PLACES"]["amount"]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

Encountering a NoClassDefFoundError in Glassfish Server while trying to work with JSON objects in Java

In my project in Eclipse Neon 3.6.3, I am working with a Java EJB project that involves using Json-Objects to analyze the response from a REST-Service. I have already imported JSONObject: import org.json.JSONObject; I also included json-20160810.jar i ...

Having trouble parsing Twitter Search API JSON response with PHP?

Currently, I am utilizing the Twitter Search API 1.1 to search for tweets related to a specific keyword and showcase the results on a dedicated search results page hosted at motherpipe.co.uk. Special thanks to James Mallison from http://github.com/j7mbo/t ...

Iterate through an array to dynamically assign values to variables using string elements

I'm facing a challenge here. I need to generate 4 new elements with the same class but different IDs without repeating code. Unfortunately, my loop doesn't seem to be working as expected. I've spent the last 2 hours trying to crack this puz ...

Searching for Distinct Users Using Mongoose

Situation Within a MongoDB database, there exists a collection containing mail documents. Each of these documents contains fields for both the receiver and sender. Objective My goal is to fetch a single mail from each unique sender. This means I do no ...

Why does the name not appear when I first click the button, only 'emit'?

I am attempting to utilize eventemiter in order to send a name when clicking a button, but it doesn't seem to be working as expected. The issue I am facing is that the name is not displayed the first time I click the button, however, if I click it aga ...

The value of InlineButton should be updated in the database with the current date

I am currently working on integrating an inline button within a table that will immediately update the database with today's date when clicked. The functionality I am aiming for is to have the button "change" trigger the insertion of the current date ...

What steps do I need to take to build a Yahoo Pipe that transforms Json data into RSS format

Looking to convert JSON to RSS, and after some research I came across Yahoo Pipes as the ideal web service for this task. Unfortunately, the pipe I found did not work properly and only resulted in a null output. Check out the pipe here The URL I attempte ...

Can a client-side React component or application be hosted on a server-side Express route?

Currently, I have a Node/Express backend that utilizes Pug.js to render various server-side routes for a basic, static website. In React.js, I have developed an interactive "builder" component through CRA, enabling visitors to configure products interacti ...

Exporting multiple HighCharts visualizations to PowerPoint presentations

Our team is preparing to create an Angular-based web application featuring 15-20 unique charts utilizing HighCharts. One of the key requirements is the ability to export these charts into PowerPoint slides. We are aware that HighCharts offers an option to ...

Using MongoDB to compute the mean value of elements within nested arrays

As a newcomer to MongoDB, I am currently working on developing a function that can calculate the average marks for a student. I have formulated the following document: student = { "id": 123456, "name": "John", "surname": " ...

Fade effect on content in Bootstrap carousel

I am currently making some updates to the website mcelroymotors.com. One issue I have encountered while working on the homepage carousel is that the caption only pops up on the first slide, and does not appear on any of the subsequent slides. I would lik ...

"Exploring the Power of Node.js and Firebase for

I'm encountering some issues with Node.js, as I am fairly new to it. I am attempting to create a post method, but it keeps returning Something is not right and I'm struggling to identify the problem Here is the code snippet. exports.createN ...

Develop an AJAX script for processing multiple form inputs in PHP and HTML

I am working on a code that involves multiple form submissions, but the submit functionality is not working due to having multiple submits on one page. I have realized that I need an Ajax script to handle this, but I am new to it. Can someone provide me wi ...

I am experiencing an issue where the result is not appearing on the input tag within my

<script> <form action="do-add-cek.php" id="myForm" method="post" enctype="multipart/form-data"> <div class="form-group"> <label> ...

Activate vertical scrolling in JavaScript when an image is clicked

I currently have a collection of button images with different hover effects specified like this: <img src="home.PNG" onmouseover="this.src='homemo.PNG'" onmouseout="this.src='home.PNG'" /> My goal is to make them scroll down to ...

Send an ArrayList to jQuery Flot

Good day. Apologies for any language barriers as English is not my first language. I am a novice in [see tags] and I have a web application that gathers a date and a serial number to execute a SQL query. The query returns some data (measurement values an ...

JavaScript: The power of nested array manipulation

I'm having trouble extracting data from a parsed JSON array obtained from a shipping company. Specifically, I am attempting to retrieve the short_name of Cleveland, OH, but all my attempts to access this information have been unsuccessful. When I use: ...

Unraveling the mysteries of the spread operator in Javascript

Having trouble finding the right keyword to search for my issue, as I am confused about JavaScript or TypeScript spread operator behavior. I encountered this problem while working on a drag and drop function today, but let me provide a simple example. Imag ...

Deciding the result of a jQuery dialogue and storing the result in a variable

Instead of using a standard confirm dialog box in JavaScript, you can customize and style it using the jQuery UI dialog. Here's an example: // Initialize variable as false var shouldIngest = false; // Open jQuery UI dialog with custom styling $(&apo ...