Comparing JSON and JavaScript object arrays: Exploring the differences in outcomes and strategies for achieving desired results

Although it's not valid JSON, I've found that by declaring this as a variable directly in my code, I can treat it like an object.

<script>
//  this will result in object
    var mydata = {
        users: [{
            person: {
                firstName: "Garry",
                lastName: "Finch"
            },
            jobTitle: "Front End Technical Lead",
            twitter: "gazraa"
        }, {
            person: {
                firstName: "Hans",
                lastName: "Wurst"
            },
            jobTitle: "Photographer",
            twitter: "photobasics"
        }, {
            person: {
                firstName: "Paul",
                lastName: "Stark"
            },
            jobTitle: "LEGO Geek",
            twitter: "minifigures"
        }]
    };

    console.log('mydata: ' + mydata);
    console.log(mydata);
</script>

https://i.sstatic.net/II7ef.png

Now, I want to save the same information into a file called "table.data.js". The contents of the file would look like this:

//BEGIN
{
    users: [{
        person: {
            firstName: "Garry",
            lastName: "Finch"
        },
        jobTitle: "Front End Technical Lead",
        twitter: "gazraa"
    }, {
        person: {
            firstName: "Hans",
            lastName: "Wurst"
        },
        jobTitle: "Photographer",
        twitter: "photobasics"
    }, {
        person: {
            firstName: "Paul",
            lastName: "Stark"
        },
        jobTitle: "LEGO Geek",
        twitter: "minifigures"
    }]
}
//END

I then attempted various methods to read this file

$.ajax({
    contentType: "application/json; charset=utf-8",
    url: "Content/modules/Controls/table/table.data.js",
    data: "{}",
    dataType: "json",
    success: function(data) {
        var json = data;
        console.log(json);
    }
});

I also tried using $.get and $.getScript. However, the result was never the same object.

//var jqxhr = $.get("Content/modules/Controls/table/table.data.js", function () {
var jqxhr = $.getScript("Content/modules/Controls/table/table.data.js", function (data, textStatus, jqxhr) {
        console.log("success");
    }).done(function (data) {
        console.log(data);
        testdata = JSON.stringify(data);
        console.log(testdata);
  }).fail(function () {
      console.log("error");
  }).always(function () {
      console.log("finished");
  });

The result always ended up being plain text in the console. It seems like a simple task for some, but it's quite challenging for me.

EDIT: Thank you to everyone who responded. In conclusion, it seems that it's not possible to load external data, store it in a variable like "mydata", and have it behave the same way as when declared directly in the code. I'll convert the data to valid JSON instead.

If I were to give a medal for the shortest and most precise answer, it would go to @Quentin. But, thank you all for your insights.

Answer №1

Uh oh, looks like your file isn't valid JSON because you forgot to enclose your property names in quotes.

Also, your file isn't valid JavaScript since an object literal can't just float around aimlessly - it needs to be assigned to something on the left side at least.

To fix this issue, make sure your file is either valid JSON or valid JavaScript (JSON is recommended).

Answer №2

JSON serves as a serialized representation of hierarchical data, allowing for the storage of hierarchical structures like objects in string format. This enables easy serialization and transmission over networks.

If you are storing your data as a JavaScript object, you can reference it in other scripts by either setting it as a global variable or exposing a function to retrieve the data. This provides access to the data within the same scope across multiple files.

<script src='./path/to/data.js'></script>
<script>
    console.log(data);
</script>

In your data.js file:

data =     {
    users: [{
        person: {
            firstName: "Garry",
            lastName: "Finch"
        },
        jobTitle: "Front End Technical Lead",
        twitter: "gazraa"
    }, {
        person: {
            firstName: "Hans",
            lastName: "Wurst"
        },
        jobTitle: "Photographer",
        twitter: "photobasics"
    }, {
        person: {
            firstName: "Paul",
            lastName: "Stark"
        },
        jobTitle: "LEGO Geek",
        twitter: "minifigures"
    }]
};

If utilizing a JSON file, ensure its structure follows this format:

{
    "users": [
    {
        "person": {
        "firstName": "Garry",
        "lastName": "Finch"
        },
        "jobTitle": "Front End Technical Lead",
        "twitter": "gazraa"
    },
    {
        "person": {
        "firstName": "Hans",
        "lastName": "Wurst"
        },
        "jobTitle": "Photographer",
        "twitter": "photobasics"
    },
    {
        "person": {
        "firstName": "Paul",
        "lastName": "Stark"
        },
        "jobTitle": "LEGO Geek",
        "twitter": "minifigures"
    }
    ]
}

The key distinction in a JSON file is the use of quotes around object keys. To achieve this format, execute JSON.stringify(data) (with your JS object as data) in the console to receive a JSON string.

If your file adheres to JSON formatting, use AJAX methods shown in your question to fetch the data. Certain libraries may automatically handle JSON.parse based on response headers, such as jQuery.

Answer №3

Consider enclosing all keys in the JavaScript file within double quotes, for example "users": [{ "person": { and so on.

Despite its appearance similar to JavaScript, JSON is a specific data format with distinct rules of its own.

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

Struggling to render images within a child component in a React application when passed as a prop from the parent component

Currently immersed in a React project, here is the structured layout of my work: public index.html src App.js images facebook.png image.PNG linkedin.png profile.png twitter.png Profile Intro profileIntro.js data data.js Within App.js, I import ...

I am facing an issue with file manipulation within a loop

I need to set up a folder with different files each time the script runs. The script should not run if the folder already exists. When I run the script, an asynchronous function is called and one part of this function causes an issue... This is my code : ...

Exploring hierarchical information within a JSON response from a Wiki API

As a newcomer to this field, I am currently exploring ways to access Wikipedia's API for extracting the value of "extract" and adding it to an HTML element dynamically. The challenge lies in the fact that the information is subject to change based on ...

What is the best way to tally jsonObject instances within the same array based on their id or value

I have a jsonDataArray that contains two nested arrays with objects. My goal is to calculate the number of "duty" parentIds based on the teams' "value" as they have a one-to-one match. For instance, Team A with a value of 500 will have duties such as ...

The Ajax request failed to retrieve any data

I'm attempting to modify data after clicking on a div, however I am not seeing any changes in the results JavaScript code $(document).ready(function() { $('#piso .caixa').click(function() { var valorpiso = $(this).text(); ...

Unable to locate a contact within the state

Currently, I am diving into the world of React by exploring its documentation and challenging myself to build a small chat application. While I have a good grasp on the basics, I am encountering some issues with states. Within my code, there is an object ...

non-concurrent in Node.js and JavaScript

I'm a beginner in the world of NodeJS and I have a question that's been bugging me. Node is known for its asynchronous nature, but JavaScript itself also has asynchronous features (like setTimeout). So why weren't concepts like Promise intr ...

Implement and remove changes in mongodb

My database sample looks like this: db={ "sample": [ { current_book: "Aurthor", upcoming_book: [ "Sigma", "Rocky" ] } ] } I am trying to update the current_book value to ...

Invalid JSON syntax: found an unexpected token, the letter

JSON.parse() doesn't seem to be functioning properly within my code, and I'm unsure of the root cause. JavaScript Code: var obj = JSON.parse(this.responseText); console.log(obj.status + " " + obj.type); if (obj.status == "success") { documen ...

Using NSJSONSerialization with an integer value

I have been working on an iOS app that fetches data from a web request. Upon receiving the response, the data looks like this: {"hash":"0369a5d5e65335309b2b1502dc96b5aba691b9451c83b9","error":0} To extract the data from the NSData* responseData object, I ...

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

Submitting forms using Curl instead of Ajax

I need to use AJAX to submit form data with a file to a controller, which will then send the data to my API using cURL. How can I achieve this? Unfortunately, I am unable to directly submit the form data to my API; it must first pass through the controlle ...

What is the best method for sending JSON files to Splunk Enterprise from a Java application?

As a novice, I am in the process of setting up a system to collect and parse JSON files using JAVA (Spring batch). However, I have run into a roadblock when trying to send these files to the HTTP EVENT COLLECTOR (HEC) in Splunk enterprise. Despite search ...

Chrome PWA debugger fails to respond when attempting to use the "add to homescreen" button

I have been endeavoring to implement the "add to Homescreen" prompt feature on my website. After thoroughly reviewing Google developer documentation, I have successfully configured everything accordingly. However, when I try to manually add my page to the ...

Discrepancy in functionality between Android and JavaScript Parse API

Using the open source version of Parse Server as a back end, my Android application saves objects to the server's DB in the form of key-value pairs encoded as JSON. However, when trying to retrieve the same object from an Ionic 2 app using the JS Pars ...

PHP is consistently failing to decode a JSON object generated by JavaScript, with the error code always being 4

In my JavaScript code, I am working on creating a map of key and value pairs. To achieve this, I create an object and store it in a hidden textarea. My intention is to retrieve the data using PHP, decode the object, and ultimately save it to a database. Th ...

Postponing the AJAX request in jQuery/Coffeescript

Here is some code in javascript/jquery/coffescript that is responsible for sliding in a DIV on the lower part of a webpage after a certain delay. This code also includes a call to an endpoint in a Ruby on Rails application to increment a view counter in th ...

The Django user object cannot be looped through or converted into a serialized form

Just starting out with Django and I'm encountering an issue with my views.py file. def edituser(request, id): member = User.objects.get(id=id) return JsonResponse(member, safe=False) I keep getting the error message: "Object of type User is n ...

Serializing a JSON object to a C# class

Currently, I am tackling the task of deserializing a Json Object into a class in .NET Visual Studio 2015 on Windows 7. public class1 { [JsonProperty(TypeNameHandling = TypeNameHandling.Objects)] public Class1 data1; public Class2 data2; } pub ...

Can you explain the JSON serialization that is likely to occur for a 'oneof' protobuf field?

Consider a .proto file with the following structure: syntax = "proto3"; message Foo { ... } message Bar { ... } message Msg { string baz = 1; oneof some_union { Foo foo = 2; Bar bar = 3; } } How should a message of this type be ser ...