Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly.

The Users table has been created with the name "Users".

Below is the content of UsersCreateTable.html:

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />

    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

    <script>
AWS.config.update({
  region: "us-west-2",
  endpoint: 'http://localhost:8000/',
  accessKeyId: "fakeMyKeyId",
  secretAccessKey: "fakeSecretAccessKey"
});

var dynamodb = new AWS.DynamoDB();

function createUsers() {
    var params = {
        TableName : "Users",
        KeySchema: [
            { AttributeName: "id", KeyType: "HASH"}
        ],
        AttributeDefinitions: [
            { AttributeName: "id", AttributeType: "N" }
        ],
        ProvisionedThroughput: {
            ReadCapacityUnits: 5,
            WriteCapacityUnits: 5
        }
    };

    dynamodb.createTable(params, function(err, data) {
        if (err) {
            document.getElementById('textarea').innerHTML = "Unable to create users table: " + "\n" + JSON.stringify(err, undefined, 2);
        } else {
            document.getElementById('textarea').innerHTML = "Created users table: " + "\n" + JSON.stringify(data, undefined, 2);
        }
    });
}

    </script>

    <title></title>
</head>
<body>

    <input id="createTableButton" type="button" value="Create Table" onclick="createUsers();" />
    <br><br>
<textarea readonly id="textarea" style="width:400px; height:800px"></textarea>


</body>
</html>

I have already prepared sample JSON data for our Users Table. To load this JSON Users Data into DynamoDB local, I modified their MoviesLoadTable.html to UsersLoadTable.html file.

However, when attempting to load the JSON data, console errors are displayed:

Uncaught SyntaxError: Unexpected token : in JSON at position 497
    at JSON.parse (<anonymous>)
    at FileReader.r.onload (UsersLoadData.html:31)
r.onload @ UsersLoadData.html:31
FileReader (async)
processFile @ UsersLoadData.html:53

Content of UsersLoadData.html:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />

    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.7.16.min.js"></script>

    <script type="text/javascript">
AWS.config.update({
  region: "us-west-2",
  endpoint: 'http://localhost:8000/',
  accessKeyId: "fakeMyKeyId",
  secretAccessKey: "fakeSecretAccessKey"
});

var docClient = new AWS.DynamoDB.DocumentClient();

function processFile(evt) {
    document.getElementById('textarea').innerHTML = "";
    document.getElementById('textarea').innerHTML += "Importing users into DynamoDB. Please wait..." + "\n";
    var file = evt.target.files[0];
    if (file) {
        var r = new FileReader();
        r.onload = function(e) {
            var contents = e.target.result;
            var allUsers = JSON.parse(contents);

            allUsers.forEach(function (user) {
                document.getElementById('textarea').innerHTML += "Processing user id: " + user.id + "\n";
                var params = {
                    TableName: "Users",
                    Item: {
                        "id": user.id,
                        "info": user.info
                    }
                };
                docClient.put(params, function (err, data) {
                    if (err) {
                        document.getElementById('textarea').innerHTML += "Unable to add user: " + count + user.id + "\n";
                        document.getElementById('textarea').innerHTML += "Error JSON: " + JSON.stringify(err) + "\n";
                    } else {
                        document.getElementById('textarea').innerHTML += "Loading succeeded(id): " + user.id + "\n";
                        textarea.scrollTop = textarea.scrollHeight;
                    }
                });
            });
    };
        r.readAsText(file);
    } else {
        alert("Could not read users data file");
    }
}

    </script>

    <title></title>
</head>
<body>

    <input type="file" id="fileinput" accept='application/json' />
    <br><br>
<textarea readonly id="textarea" style="width:400px; height:800px"></textarea>

    <script>
        document.getElementById('fileinput').addEventListener('change', processFile, false);
    </script>

</body>
</html>

I've tried troubleshooting the error without much success. Any help provided would be greatly appreciated. Thank you.

Answer №1

Your JSON data appears to have an invalid format: https://i.stack.imgur.com/oHyKy.png

Below is the corrected JSON structure:


[
    {
        "id": 1,
        "info": {
            "name": "John",
            "surname": "Smith",
            "city": "NY",
            "birthday": "26/07/1996",
            "activities": [
                "Basketball",
                "Cinema",
                "NightOut"
            ],
            "badges": ["Friendly Player", "Basketball Pro"],
            "reviews": ["Came to event on time", "Good basketball player", "I didn't like him", "Didn't show up on time"],
            "connections(id)": [2, 3, 4],
            "events": [
                { "place": "Some Place", "date": "10/10/2017", "time": "18:00", "activity": "Basketball" },
                { "place": "Another Place", "date": "13/10/2017", "time": "21:00", "activity": "Cinema" },
                { "place": "Third Place", "date": "19/10/2017", "time": "22:00", "activity": "NightOut" }
            ]
        }
    },

    {
        "id": 2,
        "info": {
            "name": "Adam",
            "surname": "Williams",
            "city": "San Francisco",
            "birthday": "Unknown",
            "activities": ["Tennis", "NightOut"],
            "badges": ["Friendly Player", "Tennis Pro"],
            "reviews": ["Adam is the best", "Best tennis player ever", "Don't play tennis with this guy"],
            "connections(id)": [1, 3, 4],
            "events": [
                { "place": "Tennis Place", "date": "01/03/2018", "time": "20:00", "activity": "Tennis" },
                { "place": "Nightout Place", "date": "03/03/2018", "time": "20:00", "activity": "NightOut" }
            ]
        }
    },
    
    // Additional records omitted for brevity 

]

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

Dealing with information obtained through ajax requests

Trying to send data from modal using ajax. Below is the code snippet I am using, however, it seems that the first IF block is causing issues. If I comment it out, I can access the $_POST['id'] variable, but otherwise, it doesn't work. ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

Is there a way to modify the state following a sorting operation?

How can I properly update the state after sorting by salary? state = { workers: [ {name: 'Bob', surname: 'Meljanski', salary: 5140}, {name: 'Michel', surname: 'Hensson', salary: 5420}, {n ...

Cross-origin resource sharing (CORS) allows for the secure transfer of data across different

Currently, I am faced with a challenge in making an XmlHTTPRequest POST request from a page loaded via HTTPS to a different domain using an HTTP URL. The HTTP server in question is local and does not support HTTPS due to being within a home setup (like a s ...

Ways to filter out specific fields when returning query results using Mongoose

I was wondering about the code snippet below: Post.create(req.body) .then(post => res.status(201).json(post)) .catch(err => res.status(500).json(err)) While this code works perfectly, I am curious about excluding a specific field, such as the __v fi ...

Searching through multiple sub-documents using MongoDB filters

I have a specific dataset stored in mongo DB that contains information on fruits and cars, with an indication of their active status. My goal is to filter this data to display only the active subdocuments, which include active cars and active fruits. ...

Issue encountered while appending new rows to the tbody of a table

I'm encountering an issue with the append function within a for loop in my code. The string being passed to the function isn't parsing correctly and results in an error. How can I go about resolving this problem? Thanks! function getDetailPopUp ...

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

Embed script tags into static HTML files served by a Node.js server

Looking to set up a Node server where users can request multiple pages from a static folder, and have the server inject a custom tag before serving them. Has anyone had success doing this? I've tried with http-proxy without success - not sure if a pro ...

Creating an interactive quiz using JSON and distributing the results from a SQL query into a multidimensional array

Working on a quiz system that stores questions and answers in a MySQL database has led me to try and convert the data into a multidimensional array and then into JSON format. However, the result is not meeting my expectations and I'm stuck with the cu ...

After clearing the option, the onChange function stops functioning

I'm facing an issue with the following code: success: function (data) { $('#' + idDivRefresh).endLoading(); if (data.message != '@Geral.Sucesso') { $('#' + idDropDown + ...

Why does the CLI crash when attempting to retrieve all data from an Oracle Database with JQuery?

Trying to utilize JavaScript and Jquery for database search, a generic query.php file has been set up to pass in the database and query, returning an array. Strangely, when attempting to select all using *, the PHP server crashes with: https://i.stack.img ...

JavaScript code that iterates through all files in a designated folder and its subfolders using a for loop

I am looking to combine two JavaScript scripts into one, but I'm not sure how to do it. The first script uploads files from a specified folder to VirusTotal for scanning and returns the scan result. The second script lists all files in the specified ...

Close session when browser/tab is exited

After extensive searching online, I have been unable to find a satisfactory solution for ending a session when a browser or tab is closed without requiring the user to log off. I have attempted numerous JavaScript codes that I came across, but none of the ...

Include a stylesheet as a prop when rendering a functional component

Using Next.js, React, Styled JSX, and Postcss, I encountered an issue while trying to style an imported component for a specific page. Since the stylesheets are generated for a specific component at render time, I attempted to include custom styles for the ...

Ensure that the package.json file contains a "builds" section by using the jq command

Currently, I am working on writing a shell script that will verify the existence of a 'builds' key within the 'package.json' file for an NPM project. In order to accomplish this task, I am utilizing the 'has' function from &ap ...

Retrieving status code without reliance on a back-end language (maybe through JavaScript?)

My new service offers a solution for error pages in web apps by providing a code snippet that can be easily copied and pasted into the error page templates, similar to Google Analytics. The status code is embedded in a hidden input within the installatio ...

Accessing the page directly in a Nuxt SPA is not permitted

I'm currently working with Nuxt version 2.3.4. In my project, I am utilizing vue-apollo to fetch data for a file named pages/_.vue, which dynamically manages content. As indicated on this documentation page, this is the recommended approach for handli ...

Is it possible to enable tab navigation for a button located within a div when the div is in focus?

I have a component set up like this: (Check out the Code Sandbox example here: https://codesandbox.io/s/boring-platform-1ry6b2?file=/src/App.js) The section highlighted in green is a div. Here is the code snippet: import { useState } from "react" ...

Using python to scrape images from a website with AJAX using selenium and beautifulsoup

After spending a considerable amount of time delving into html, javascript, network traffic, and expanding my knowledge on javascript, blobs, and base64 encoding/decoding of images, I am still struggling to extract images from videos on a particular websit ...