【问题标题】:Generating value in json format from database column [closed]从数据库列生成 json 格式的值 [关闭]
【发布时间】:2020-10-20 18:22:22
【问题描述】:

我在table 中有一个column,名称为canonicalName,其中包含Vision Canadaapple computers 之类的值。表包含大约 10k 条记录。我必须以以下格式将这些值传递给 API。我正在使用oracle 数据库表。表名是Organization

{
     "add": [        

        {
            "canonicalName": "Vision Canada"
            
        },
        {
            "canonicalName": "apple computers",                       
        }
    ]
}

你能建议我如何在 Java 中生成相同的内容

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    在不知道表格来自哪个数据源的情况下,很难给出真正具体的答案,但这是我在 javascript 中的最佳选择:

    const columnName = 'canonicalName' // Get this once from your table
    const arrayOfColumnValues = ['Vision Canada', 'Apple Computer'] // However you get your values out of the table they should be in an array like so
    
    // This array will hold all of the { 'canonicalName' : 'x' } fields in the 'Add': [] you need to pass to the API
    const arrayOfColumnObjects = []
    
    // Here we iterate through each value from the column in the table and send it to the object array.
    // {[columnName]: value} sets the key to the VARIABLE 'columnName'.
    // This is different than saying {columnName: value} which would set the key to the STRING "columnName".
    arrayOfColumnValues.forEach(value => arrayOfColumnObjects.push({[columnName]: value}))
    
    // Then we wrap the arrayOfColumnObjects in the object we need to send it to the API like so
    const apiJsonObject = {
        Add: arrayOfColumnObjects
    }
    
    // Of course here you would return it instead of logging
    console.log(apiJsonObject)
    

    JS Fiddle

    【讨论】:

    • 谢谢詹姆斯。它的 Oracle 数据库表。
    • @ShrutiSharma 我对 OracleDB 一无所知,但如果您使用的是 Node.js,您可以尝试一下吗? github.com/oracle/node-oracledb/blob/master/doc/api.md
    • 这些不是静态值詹姆斯。我们将不得不从数据库中读取值。
    • 我知道,您将需要一个可以从您的数据库中读取值的库,类似于我上面链接的那个。只要您可以将数据库中的数据以数组的形式插入,我的其余代码仍然可以为您工作。我无法为您编写完整的实现,因为我不知道您将使用哪个库,也不知道您的数据库的结构。希望我的回答为您指明了正确的方向。
    猜你喜欢
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2011-04-24
    相关资源
    最近更新 更多