Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = {
  
  "@type": "Movie",
  "url": "/title/tt0443272/",
  "name": "Lincoln",
  "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA@@._V1_.jpg",
  "description": "As the American Civil War continues to rage, America's president struggles with continuing carnage on the battlefield as he fights with many inside his own cabinet on the decision to emancipate the slaves.",
   
 
 
  
  "duration": "PT2H30M"
}


console.log(info["@type"])

I have extracted a large JSON data but I am unsure how to access values where keys start with "@".

How can I retrieve the value of "@type"?

When I attempt this method, I encounter an error:

SyntaxError: Invalid or unexpected token

Answer №1

In JavaScript, variables must begin with a letter, dollar sign, or underscore.

If you have an invalid variable name, you cannot access it using dot notation and instead must use bracket notation.

Example of an invalid variable:

data.@type

To correct this, you should use:

data['@type']

Answer №2

If you want to check the data type, simply use console.log(data['@type'])

let data = {
  "@type": "Movie",
  "url": "/title/tt0443272/",
  "name": "Lincoln",
  "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA@@._V1_.jpg",
  "description": "As the American Civil War continues to rage, America's president struggles with continuing carnage on the battlefield as he fights with many inside his own cabinet on the decision to emancipate the slaves.",
  "duration": "PT2H30M"
}


console.log(data['@type'])

Answer №3

To retrieve variable properties, you have the option of using bracket notation to access them as key-value pairs:

let info = {

    "@genre": "Comedy",
    "link": "/title/tt0443272/",
    "title": "The Hangover",
    "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA@@._V1_.jpg",
    "plot": "Three groomsmen lose their about-to-be-wed buddy during his bachelor party in Las Vegas, then must retrace their steps to find him.",

    "runTime": "PT1H30M"
}


console.log(info["@genre"])

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

Binding JSON data to model properties using JsonProperty

As part of the agreements between my party and the client, I am required to use JSON parameters with dashes. However, since C# does not allow property names with dashes, I need to find a way to map them properly. Current Procedure: The following code h ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

display saved data from ajax request

I've been working on saving data and files using ajax. Following a tutorial (link), I managed to successfully save the data in the database and the image files in the designated folder. However, I'm facing an issue where the success or error mess ...

Error encountered in Chrome while trying to fetch Next.js PWA with the use of next-pwa: Unhandled TypeError

Hello, I was recently working on a Next.js project and attempted to convert it into a PWA using next-pwa. To start off, I created the next.config.js file. const withPWA = require('next- pwa'); module.exports = withPWA({ pwa: { dest: ...

Is the risk of using deprecated synchronous calls on the main thread worth it in JavaScript?

I have created a single page web application that relies on modifying a section of the page and then calling specific functions to format this section after it has been modified. One of the crucial post-modification calls I need to make is MathJax. Howeve ...

The NextJS development server is frequently losing connection

Issue While working on my NextJS project, I've been experiencing occasional disruptions with my development server. Whenever I update my code, I encounter random occurrences of the dev server disconnecting and displaying the error message below: Type ...

What could be causing the server to not successfully receive the ajax request?

I need to conduct integration tests on a website that routes all requests through a proxy: var express = require("express"), http = require("http"), port = (process.env.PORT || 8001), server = module.exports = express(), httpProxy = requir ...

Issue: Entering data in the input field for each row results in the same value being copied to the qty field

Currently, I have a field where users can enter the quantity for each row. Everything was functioning properly until I decided to add another input field for the pick option. Unfortunately, now it seems that whatever is entered in one field gets duplicated ...

An easy and Pythonic method to beautifully format response headers from requests

I am struggling to format the HTTP response from Python's Requests library in a clean and Pythonic way without relying on external packages. I keep running into issues with the JSON formatting. What I have attempted: I tried converting response.head ...

What are some ways I can effectively implement Tanstack Query's useMutation function?

I am trying to implement useMutation similar to useQuery in my code. However, I encountered an issue where the data is returning as undefined and isError is false. Can anyone help me understand why this is happening and how I can resolve it? `import { us ...

Difficulty unraveling JSON using Codable. Error message indicating keyNotFound

I'm facing an issue when it comes to decoding JSON. I've been attempting to decode my JSON using let temp = try JSONDecoder().decode([LastTemperatureResponse].self, from: data). The Codable structs I'm working with are as follows: struct ...

Encoding identification data from JSON using ColdFusion

Hello everyone, I've been puzzling over how to intercept and encrypt database record ID from a JSON request in ColdFusion. Below is the code I have so far, along with my unsuccessful attempt. Any assistance would be greatly appreciated. <cfquery ...

What is the proper way to generate an iframe with a width set to "100%" or left empty, rather than width = "100"?

I am currently utilizing vimeowrap to iterate through a playlist of videos. I would like the iframe that is generated by vimeowrap to have either a width and height set to "100%" or nothing at all. For more information on Vimeo Wrap, visit: To see my tes ...

Issue with Unslider functionality when using navigation buttons

I've implemented the OpenSource "unslider" to create sliding images with navigation buttons, but I'm facing an issue with the code provided on http:www.unslider.com regarding "Adding previous/next lines." Here are the CSS rules and HTML tags I h ...

Is there a way to replicate ajaxStart and ajaxStop functions without using jQuery?

After reviewing the extensive jQuery code, I'm wondering if this task would be simple to accomplish. Any suggestions on how to approach it? I'm interested in using this not for a webpage, but for a C# application that needs to monitor ajax activ ...

Associate the ng-model with ng-options value and label

I'm currently using ng-options to create a select tag that displays location options. The labels represent the location names, while the values indicate the corresponding location ID as stored in the database. In addition to binding the value (locati ...

What is the best way to trigger the download of an image file created by PHP to a user's computer?

My PHP code (upload.php) allows users to upload an image from index.html, resize it, add a watermark, and display it on the same page. Users can download the watermarked image by using the 'Save image as...' option. The resized image is saved in ...

Just-In-Time Compilation: The most efficient method for converting data to JSON format

I am working on generating a custom JSON for the jit library. I am contemplating whether to incorporate additional C# logic or find a way to extend the JsonSerializer. The structure of the desired JSON is shown below: var json = { "children": [ { ...

Filtering JSON data in AngularJS is simple and effective

I am working with JSON data and I want to display it filtered by genre. The solution provided in the previous question How to filter JSON-Data with AngularJs? did not work for me. Here is myapp.js: var myApp = angular.module('myApp', []); myAp ...

Styling Your Navigation Bar with CSS and Active States

Creating an interactive navigation element for a menu can be challenging, but here's a helpful example. http://jsfiddle.net/6nEB6/38/ <ul> <li><a href="" title="Home">Home</a></li> <li class="activ ...