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

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

What is the best way to transform a BLOB Buffer into a Base64 string using Swift?

I am facing an issue where I have stored a base64 string as a BLOB in Swift, but now I am struggling to figure out how to convert the buffered blob back into a UIImage. When storing it, Blob converts it into buffer, here is what I did: let image: UII ...

The distinction between a keypress event and a click event

Due to my eyesight challenges, I am focusing on keyboard events for this question. When I set up a click event handler for a button like this: $("#button").on("click", function() { alert("clicked"); }); Since using the mouse is not an option for me, ...

Minimize the gap between legend text and icon in Highchart

Is there a way to decrease the space between the number and icon? I am currently working with Angular 8 and Highchart. Below is the configuration of the chart legend. https://i.stack.imgur.com/0dL7y.jpg this.legend = { align: 'center', verti ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

No instances are returned by Processing.instances

I am experiencing an issue with a webpage that is running 2 processing sketches. I came across a suggestion to call Processing.instances[0].exit() in response to a question on dynamically unloading a Processing JS sketch from canvas. However, when I attem ...

The issue with onclientclick in Asp.Net button

I am experiencing a peculiar problem that I cannot seem to solve. The issue revolves around a button that I have implemented using the following code: <asp:Button ID="btnSave" runat="server" ClientIDMode="Static" Text="Save" OnClientClick="return Confi ...

sending a POST request with multiple parts using d3.json() or d3.xhr()

Currently, there seems to be a lack of support for submitting multipart form data with a request. While I understand how to perform a POST with d3.json().post() as outlined in this resource, I am specifically interested in using POST to submit parameters t ...

Send a response from socket.io to the client's browser

I am working on a project where I need to retrieve the ID of the current drawer from the server and pass it to the client. Here is the code I have so far: Client Side: socket.emit('returnDrawer'); socket.on('returnDrawer', fu ...

Titanium: Picture -> "automatically"

Imagine there is an image named hello.png with the dimensions of 200x100. A button is then created using this hello.png as shown below: var btn = Titanium.UI.createButton({ bottom : 50, backgroundImage : "images/hello.png", width:100, height:"auto"; }); w ...

`Some Items Missing from Responsive Navigation Menu`

Hey there! I'm currently diving into the world of responsive design and I'm attempting to create a navigation bar that transforms into a menu when viewed on a mobile device or phone. Everything seems to be working fine, except that not all the na ...

Determining the scrollWidth of a div with an absolutely positioned child div

Having some trouble determining the width of a div's content instead of the div itself. The typical solution would involve using Javascript's scrollWidth property. However, there is a complication in this case. Inside the div, another div is ab ...

The antithesis of jQuery's .parents() selector

I am currently developing a userscript for a webpage with an old-fashioned design consisting mainly of tables. My goal is to access a long table of fields so that they can be filled in automatically by the script. To simplify, the structure is as follows: ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

The Angular performance may be impacted by the constant recalculation of ngStyle when clicking on various input fields

I am facing a frustrating performance issue. Within my component, I have implemented ngStyle and I would rather not rewrite it. However, every time I interact with random input fields on the same page (even from another component), the ngStyle recalculate ...

Learn how to create a dynamic React.useState function that allows for an unlimited number of input types sourced from a content management system

Currently, I am exploring the possibility of dynamically creating checkbox fields in a form using DatoCMS and the repeater module. My idea is to generate multiple checkbox fields based on the input from a text field in Dato as a repeater, which can then be ...

Sending an object along with additional variables back to the client through JSON serialization: Tips and Tricks

What is the best way to incorporate the dictionary a into the response, and how can I retrieve two objects through an ajax call? view def abc(request): cp = Cp.objects.get(id=1) cp = serializers.serialize('json', [cp,]) cp = json.lo ...

From HTML to Python to Serial with WebIOPi

I am facing a dilemma and seeking help. Thank you in advance for any guidance! My project involves mounting a raspberry pi 2 b+ on an RC Crawler rover, utilizing WebIOPi for the task. However, I am encountering challenges and unable to find useful resourc ...

Merging pertinent information from separate arrays

Seeking assistance in merging data from two distinct arrays with varying structures. Data is acquired via API, the initial request: [ { "category_id": "12345", "category_name": "itemgroup 1", "cat ...