I found your unanswered question today, and kept looking until I found an answer. Probably too late for you but may help others.

aws dynamodb create-table --cli-input-json file://tabledefinition.json

This command expects a json object in the file in the format outlined by the following command:

aws dynamodb create-table --generate-cli-skeleton

This approach seems to work with many aws commands.

Answer from Keith Branton on Stack Overflow
🌐
AWS
aws.amazon.com › blogs › database › working-with-json-data-in-amazon-dynamodb
Working with JSON data in Amazon DynamoDB | Amazon Web Services
May 1, 2023 - Amazon DynamoDB allows you to store JSON objects into attributes and perform many operations on these objects, including filtering, updating, and deleting. This is a very powerful capability because it allows applications to store objects (JSON data, arrays) directly into DynamoDB tables, and ...
Discussions

Write a JSON File as a DynamoDB Table Item - AWS - HashiCorp Discuss
I have an application that can read a JSON file from a DynamoDB table item at startup and use it for configuration. I have a dynamodb table that has 2 columns, “id” and “json”. I need to insert a value into that file using the template function for Terraform for a server url. More on discuss.hashicorp.com
🌐 discuss.hashicorp.com
0
July 6, 2021
Creating Amazon DynamoDB Table Items from a JSON File - Stack Overflow
Another possibility would be to iterate through the json with a loop and write each element individually into the database. Since this would require 100,000 writes, I am now looking for an alternative. What is the possibility to solve this problem quickly and efficiently? ... Be aware that you can temporarily increase a DynamoDB table's write capacity for ingestion. Example ... More on stackoverflow.com
🌐 stackoverflow.com
java - Create dynamodb table from JSON - Stack Overflow
I'm trying to create a dynamo table in my code through a JSON file which contains the structure of my table. More on stackoverflow.com
🌐 stackoverflow.com
Exporting Spark dataframe to AWS DynamoDB?
We have been using https://github.com/awslabs/emr-dynamodb-connector/releases for years. More on reddit.com
🌐 r/apachespark
16
9
March 19, 2023
Top answer
1 of 2
43

I found your unanswered question today, and kept looking until I found an answer. Probably too late for you but may help others.

aws dynamodb create-table --cli-input-json file://tabledefinition.json

This command expects a json object in the file in the format outlined by the following command:

aws dynamodb create-table --generate-cli-skeleton

This approach seems to work with many aws commands.

2 of 2
0

I wrote a Python script for this. My version is for yaml, but can easily be adapted to json.

Single dependency for parsing the template, with thanks to this SO post

pip install cfn_flip

#!/usr/bin/env python

import subprocess
import time
import yaml
from cfn_tools import load_yaml, dump_yaml

template_file = open('./template.yaml')
template = load_yaml(template_file.read())

for resource_key in template["Resources"]:
  resource = template["Resources"][resource_key]
  if resource["Type"] != 'AWS::DynamoDB::Table':
    continue
  
  table_name = resource["Properties"]["TableName"]
  print(f'Creating table "{table_name}"')
  
  table_definition = template["Resources"][resource_key]["Properties"]
  time_to_live_definition = table_definition.get("TimeToLiveSpecification")
  if time_to_live_definition:
    # TimeToLiveSpecification is not accepted by create-table, it is a separate command
    del(table_definition["TimeToLiveSpecification"])

  subprocess.run(["aws", "dynamodb", "create-table", "--cli-input-yaml",dump_yaml(table_definition)])
  if time_to_live_definition:
    time_to_live_definition = {
      "TableName": table_name,
      "TimeToLiveSpecification": time_to_live_definition
    }
    subprocess.run(["aws", "dynamodb", "update-time-to-live", "--cli-input-yaml", dump_yaml(time_to_live_definition)])
  
  # Tables are created asynch, give some time to complete
  time.sleep(1)

The sleep at the end is for following warning mentioned in the help of create-table. I have only tested this locally so far, so a smarter way to wait for completion might be needed.

You can optionally define secondary indexes on the new table, as part of the "CreateTable" operation. If you want to create multiple tables with secondary indexes on them, you must create the tables sequentially. Only one table with secondary indexes can be in the "CREATING" state at any given time.

🌐
AWS
docs.aws.amazon.com › amazon dynamodb › api reference › actions › amazon dynamodb › describetable
DescribeTable - Amazon DynamoDB
If you issue a DescribeTable request ... request, DynamoDB might return a ResourceNotFoundException. This is because DescribeTable uses an eventually consistent query, and the metadata for your table might not be available at that moment. Wait for a few seconds, and then try the DescribeTable request again. ... The request accepts the following data in JSON ...
🌐
YouTube
youtube.com › daniel rothamel
How to Create a DynamoDB Table Using Python and JSON in AWS Cloud9 - YouTube
In this screencast, I'll show you how to create a DynamoDB table in AWS Cloud9 by using Python scripts and a JSON data file. This is a foundational exercise ...
Published   August 4, 2021
Views   1K
🌐
AWS
docs.aws.amazon.com › aws sdk for .net › developer guide › work with aws services in the aws sdk for .net › code examples with guidance for the aws sdk for .net › using amazon dynamodb nosql databases › json support in amazon dynamodb
JSON support in Amazon DynamoDB - AWS SDK for .NET (V3)
To determine the table to get the item from, the LoadTable method of the Table class uses an instance of the AmazonDynamoDBClient class and the name of the target table in DynamoDB. The following example shows how to use JSON format to insert an item into a DynamoDB table:
🌐
Codemia
codemia.io › knowledge-hub › path › create_a_dynamodb_table_from_json
Create a DynamoDB table from json
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
Find elsewhere
🌐
GitHub
gist.github.com › sonjisov › effbb1e62b75fdcbcb23700ea988b572
Deploying a DynamoDB table using a JSON definition file · GitHub
February 23, 2022 - Deploying a DynamoDB table using a JSON definition file · Raw · deploy-dynamodb-table.sh · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
AWS
docs.aws.amazon.com › amazon dynamodb › developer guide › using dynamodb with other aws services › integrating dynamodb with amazon s3 › dynamodb data export to amazon s3: how it works › dynamodb table export output format
DynamoDB table export output format - Amazon DynamoDB
A table export in DynamoDB JSON format consists of multiple Item objects. Each individual object is in DynamoDB's standard marshalled JSON format. When creating custom parsers for DynamoDB JSON export data, the format is JSON lines · . This means that newlines are used as item delimiters. Many AWS services, such as Athena and AWS Glue, will parse this format automatically. In the following example...
🌐
DynamoDB
dynobase.dev › dynamodb-table-schema-design-tool
DynamoDB Table Schema Design Tool [Free to Use]
DynamoDB JSON that is used to create DynamoDB table requires you to understand its complicated format. This tool solve this problem by helping you design the table definition visually.
🌐
Medium
medium.com › @badawekoo › populate-dynamodb-table-items-with-single-terraform-resource-from-json-file-1dc14c830a7c
Populate Dynamodb table items with single Terraform resource from JSON file
January 9, 2023 - In this tutorial I will demonstrate how to populate data as Dynamodb table items from JSON file using single Terraform resource and for_each argument.
🌐
HashiCorp Discuss
discuss.hashicorp.com › terraform providers › aws
Write a JSON File as a DynamoDB Table Item - AWS - HashiCorp Discuss
July 6, 2021 - I have an application that can read a JSON file from a DynamoDB table item at startup and use it for configuration. I have a dynamodb table that has 2 columns, “id” and “json”. I need to insert a value into that file u…
🌐
DynamoDB
dynobase.dev › code-examples › dynamodb-query-json
[Code Examples] DynamoDB: Query JSON
But you can use the query operation to get data as an array and pass the result to JSON.stringify method to convert the array to a JSON string. const AWS = require('aws-sdk'); const dynamoDb = new AWS.DynamoDB.DocumentClient(); const params = { TableName: 'tableName', KeyConditionExpression: 'primaryKey = :primaryKeyValue', ExpressionAttributeValues: { ':primaryKeyValue': 'value' } }; dynamoDb.query(params, (error, data) => { if (error) { console.error(error); return; } console.log(JSON.stringify(data.Items)); });
🌐
AWS
docs.aws.amazon.com › amazon dynamodb › api reference › actions › amazon dynamodb › createtable
CreateTable - Amazon DynamoDB
This example creates a table named Thread. The table primary key consists of ForumName (partition key) and Subject (sort key). A local secondary index is also created; its key consists of ForumName (partition key) and LastPostDateTime (sort key). POST / HTTP/1.1 Host: dynamodb.<region>.<domain>; Accept-Encoding: identity Content-Length: <PayloadSizeBytes> User-Agent: <UserAgentString> Content-Type: application/x-amz-json...
🌐
AWS Fundamentals
awsfundamentals.com › blog › aws-dynamodb-data-types
AWS DynamoDB Data Types
September 12, 2022 - The normalized JSON view shows how you would work with the data in applications. Take the following user table as an example: You can see the userId is a string (S) while age is a number (N).
Top answer
1 of 2
2

I was also trying to achieve something similar but I didn't find any lib for that purpose, hence I took a few minutes to code it myself.

Provided with a json file structured the same way as in the documentation example:

{
    TableName : "Music",
    KeySchema: [
        {
            AttributeName: "Artist",
            KeyType: "HASH", 
        },
        {
            AttributeName: "SongTitle",
            KeyType: "RANGE" 
        }
    ],
    AttributeDefinitions: [
        {
            AttributeName: "Artist",
            AttributeType: "S"
        },
        {
            AttributeName: "SongTitle",
            AttributeType: "S"
        }
    ],
    ProvisionedThroughput: {       
        ReadCapacityUnits: 1,
        WriteCapacityUnits: 1
    }
} 

The code bellow works. Note that:

  • The createTable method expects a json string, which you can obtain using something like Files.readString(Path.of("path/to/your/file.json"))
  • if you do not use Lombok you have to create constructors/getters/setters yourself
  • the @JsonProperty annotations are only necessary if the class field names are not an exact match to the json ones (in this case, the first letter is uppercase), explained here.

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.model.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
    public class CreateTable {
        private final AmazonDynamoDB amazonDynamoDB;
    
        public void createTable(String json) throws JsonProcessingException {
            Table table = readTable(json);
            amazonDynamoDB.createTable(getTableRequest(table));
        }
    
        private CreateTableRequest getTableRequest(Table table) {
            return new CreateTableRequest()
                    .withTableName(table.getTableName())
                    .withKeySchema(toKeySchemaElement(table.getKeySchema()))
                    .withAttributeDefinitions(toAttributeDefinition(table.getAttributeDefinitions()))
                    .withProvisionedThroughput(toProvisionedThroughput(table.getProvisionedThroughput()));
        }
    
        private Table readTable(String json) throws JsonProcessingException {
            return new ObjectMapper().readValue(json, Table.class);
        }
    
        private ProvisionedThroughput toProvisionedThroughput(ProvisionedTp provisionedTp) {
            log.info("creating provisioned throughput read: {} write: {}", provisionedTp.getReadCapacityUnits(), provisionedTp.getWriteCapacityUnits());
            return new ProvisionedThroughput(provisionedTp.getReadCapacityUnits(), provisionedTp.getWriteCapacityUnits());
        }
    
        private Collection<AttributeDefinition> toAttributeDefinition(Collection<AttributeDef> attributeDefs) {
            return attributeDefs.stream().map(this::toAttributeDefinition).collect(Collectors.toList());
        }
        
        private AttributeDefinition toAttributeDefinition(AttributeDef attributeDef) {
            log.info("creating new attribute definition {}: {}", attributeDef.getAttributeName(), attributeDef.getAttributeType());
            return new AttributeDefinition().withAttributeName(attributeDef.getAttributeName()).withAttributeType(attributeDef.getAttributeType());
        }
    
        private Collection<KeySchemaElement> toKeySchemaElement(Collection<KeySchema> keySchemas) {
            return keySchemas.stream().map(this::toKeySchemaElement).collect(Collectors.toList());
        }
    
        private KeySchemaElement toKeySchemaElement(KeySchema keySchema) {
            log.info("creating new key schema element {}: {}", keySchema.getAttributeName(), keySchema.getKeyType());
            return new KeySchemaElement().withAttributeName(keySchema.getAttributeName()).withKeyType(keySchema.getKeyType());
        }
    
        @Data
        @NoArgsConstructor
        public static class Table {
            @JsonProperty("TableName")
            private String tableName;
            @JsonProperty("KeySchema")
            private List<KeySchema> keySchema;
            @JsonProperty("AttributeDefinitions")
            private List<AttributeDef> attributeDefinitions;
            @JsonProperty("ProvisionedThroughput")
            private ProvisionedTp provisionedThroughput;
        }
    
        @Data
        @NoArgsConstructor
        public static class KeySchema {
            @JsonProperty("AttributeName")
            private String attributeName;
            @JsonProperty("KeyType")
            private String keyType;
        }
    
        @Data
        @NoArgsConstructor
        public static class AttributeDef {
            @JsonProperty("AttributeName")
            private String attributeName;
            @JsonProperty("AttributeType")
            private String attributeType;
        }
    
        @Data
        @NoArgsConstructor
        public static class ProvisionedTp {
            @JsonProperty("ReadCapacityUnits")
            private long readCapacityUnits;
            @JsonProperty("WriteCapacityUnits")
            private long writeCapacityUnits;
        }
    
    }
    

  
2 of 2
1

I now this is already answered but you can use the provided class CreateTableRequest together with an object mapper such as Gson.

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class InitTables {

    private AmazonDynamoDB dynamoDB;

    private static String musicTable = "{\n" +
        "  \"TableName\" : \"Music\",\n" +
        "  \"KeySchema\": [\n" +
        "    {\n" +
        "      \"AttributeName\": \"Artist\",\n" +
        "      \"KeyType\": \"HASH\"\n" +
        "    },\n" +
        "    {\n" +
        "      \"AttributeName\": \"SongTitle\",\n" +
        "      \"KeyType\": \"RANGE\"\n" +
        "    }\n" +
        "  ],\n" +
        "  \"AttributeDefinitions\": [\n" +
        "    {\n" +
        "      \"AttributeName\": \"Artist\",\n" +
        "      \"AttributeType\": \"S\"\n" +
        "    },\n" +
        "    {\n" +
        "      \"AttributeName\": \"SongTitle\",\n" +
        "      \"AttributeType\": \"S\"\n" +
        "    }\n" +
        "  ],\n" +
        "  \"ProvisionedThroughput\": {\n" +
        "    \"ReadCapacityUnits\": 1,\n" +
        "    \"WriteCapacityUnits\": 1\n" +
        "  }\n" +
        "}";


    public InitTables(AmazonDynamoDB dynamoDB) {
        this.dynamoDB = dynamoDB;
        init();
    }

    public void init() {
        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .create();
        CreateTableRequest createTableRequest = gson.fromJson(musicTable, CreateTableRequest.class);
        dynamoDB.createTable(createTableRequest);
    }
}
🌐
Qlik Talend Help
help.qlik.com › talend components for jobs › amazon dynamodb › amazon dynamodb scenario › writing and extracting json documents from dynamodb
Writing and extracting JSON documents from DynamoDB | Talend Components for Jobs Help
... 21058;{"accountId" : "900" , "accountName" : "xxxxx" , "action" : "Create", "customerOrderNumber" : { "deliveryCode" : "261" , "deliveryId" : "313"}} 21059;{"accountId" : "901" , "accountName" : "xxxxy" , "action" : "Delete", "customerOrderNumber" : { "deliveryCode" : "262" , "deliveryId" ...
🌐
AWS
docs.aws.amazon.com › amazondynamodb › latest › developerguide › SampleData.LoadData.html
Step 2: Load data into tables - Amazon DynamoDB
May 1, 2023 - You could enter the data manually into the Amazon DynamoDB console. However, to save time, you use the AWS Command Line Interface (AWS CLI) instead. ... If you have not yet set up the AWS CLI, see Using the AWS CLI for instructions. You must create the tables before attempting to load data. If you have not created the tables, see Step 1: Create example tables. You will download a .zip archive that contains JSON ...