Struggling to create JSON functions, encountering an "Unexpected token" error while making function calls

I've been experimenting with writing functions within JSON files, but I keep encountering errors related to 'unexpected tokens'. Below is a snippet of the JSON code I'm working with:

[

    {
        "thumb": "./templates/scripts/thumbs/01.jpg",
        "get": function() {
            console.log('mthood');
        },
        "title": "Mt. Hood Sunset",
        "desc": "A peaceful view of Mt. Hood, Oregon."
    },
    {
        "thumb": "./templates/scripts/thumbs/02.jpg",
        "get": function() {
            console.log('misty');
        },
        "title": "Misty Rainforest",
        "desc": "Lush and damp surroundings."
    },
    {
        "thumb": "./templates/scripts/thumbs/03.jpg",
        "get": function() {
            console.log('clouds');
        },
        "title": "Clouds",
        "desc": "Clear blue skies with fluffy white clouds."
    }

]

As displayed by JSONLint, a more elaborate error message pops up that I find a bit puzzling:

Error: Parse error on line 5:
...s/01.jpg",       "get": function() {         cons
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

Does anyone have any thoughts or suggestions for resolving this issue?

Answer №1

In JSON, it is not possible to include functions, only non-dynamic data types such as arrays, strings, numbers, and booleans.

Answer №2

JSONLint is a tool that verifies the validity of JSON code, but it's important to note that JSON and JavaScript have some differences. While JavaScript objects may resemble JSON, they are not interchangeable. JSON strictly focuses on data exchange and does not support functions like XML does. You may test your code in Chrome's developer console, but keep in mind that it may not be considered valid JSON.

Answer №3

"I discovered a new way to utilize functions in JSON files."

There seems to be some confusion, where did you come across that information? According to the official JSON documentation, only 7 primitive types are accepted:

  • array
  • boolean
  • integer
  • number
  • null
  • object
  • string

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

Issue Encountered in AWS CloudFormation Template When Configuring EC2 Instance types

I am encountering an issue while attempting to activate the Spot Instance option in my CloudFormation template, which I then upload into AWS Service Catalog. The error pertains to my MarketType parameter, specifically within the InstanceMarketOptions Para ...

"Exploring the best way to retrieve the angular filter value within a Node.js environment

Currently, I am facing an issue with accessing the value in Node.js using req.body when it is stored in ng-model. The ng-model includes an AngularJS filter, and I need to retrieve this filtered value from the input field in Node.js through req.body. Below ...

Storing `this` in a variable that is assigned by an element using inline JavaScript is applicable for either all elements or specifically the active element that contains the assigned value

Consider this scenario: if we include the this attribute in an element's onclick event like onclick="a=this", are we selecting the "p" element or can we use the variable a as an alternative to this? Take a look at this code snippet- <p onclick=" ...

A Step-by-Step Guide to Retrieving the Route of a Controller Function in Express

When working with Express.js, it is possible to retrieve the names of all controllers from an app. However, these names are usually in an unfamiliar format (such as handle: [AsyncFunction: login]). I have been unable to figure out how to destructure this i ...

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

React router refreshes children when switching routes, without needing to reconcile

I am facing a scenario where multiple routes share the same component and I need to maintain its state, but the current behavior makes it nearly impossible. Check out this live example (observe the elapsed seconds): View the code on CodeSandbox: https:// ...

JavaScript string: Use regex to find and replace with position index

I'm not very familiar with regex, so I'm curious about the process of replacing a section in a string based on a regex pattern where the index is part of the identified section. Let's consider this example string: let exampleStr = "How do ...

Accessing the content of a jQuery editor in PHP

I have been utilizing a jquery plugin for developing a wysiwyg text editor. In my PHP code, I have created a textarea like this: <textarea name="body" id="body"><?php echo $body?></textarea> Also, added the following ...

update django model using ajax

I have a collection of articles displayed in a table on my page, and I want to implement sorting functionality using AJAX by clicking on a button. I am utilizing Dajaxice, which sends a request to ajax.py for the example1 method and receives JSON data as ...

Having trouble changing windows with WebdriverIO (Selenium)?

Currently experiencing an issue with switching between different browser tabs. The code in my test class is as follows: describe('Validate tab switching functionality', () => { beforeEach(function() { browser.url("https://duckduc ...

Creating a horizontal bar at the bottom of a webpage is a common feature that many website owners

On certain websites, I've noticed a unique feature - as I scroll halfway down the page, a semi-transparent horizontal column pops up at the bottom. This column is typically 100-150px in height and includes an image on the left with some message or lin ...

Utilizing ReactJS for Web Development with Enhanced Data Insights from Google

Utilizing Google Analytics and various tools, I've encountered an issue with the development of ReactJS. My goal was to collect analytics data from my website by using react-helmet to dynamically change the title and the HTML lang parameter based on t ...

Interacting with JSON in ASP.NET Web API

Greetings! Currently, I am in the process of developing an Azure web API and I have encountered a scenario with my PUT method. Below is the code snippet for my PUT method: public string[] Put(SampleRequest request) { //Getting Reque ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

The loading of DAE models is not supported in Three.js

I'm encountering a major issue with loading a model into Three.js. To start off, I downloaded https://github.com/mrdoob/three.js/ and extracted it onto my local WebMatrix server. Most of the examples run smoothly, except for the ones that are crucial ...

instructions on how to eliminate slideUp using jquery

I am trying to eliminate the slide-up function from my code $( document ).ready(function() { $("#tabBar ul.buttons > li > a").on("click", function(e){ //if submenu is hidden, does not have active class if(!$(this).hasClass("activ ...

I need to show the JSON object value within an Android activity

I recently delved into the world of Android development and have been trying to fetch data from a database in JSON format. However, the return value I am receiving looks like "{"users":[{"child_name":"John"}]}" when I use the following code snippet: publi ...

Calculating the sum of all values in the database

In my database, I have a value called task_time. I want to add this value to itself so that the total time is calculated as totalTime = task_time + task_time + ... + task_time. This is how I retrieve the data: function getEndTasks() { $http.get(& ...

Unable to view search results

I am having trouble with displaying the search results on my dynamic search form. Here is the jQuery code snippet I am using: $("#searchterm").keyup(function (e) { if (this.value.length > 4) { var q = $("#searchterm").val(); $( ...

How can I replace the unsightly "Web page not available" error in WebView on Android with a more visually pleasing alternative?

In my WebView Activity, I sometimes encounter issues with loading properly when the WIFI/DATA connection is poor or disconnected. This could potentially be a common occurrence once my app is in use. I'm curious to know how I can replace the unattracti ...