草庐IT

json - 尝试解析 JSON 并创建提取的 JSON

coder 2024-07-13 原文

我正在尝试根据从 API 接收到的数据动态创建一个 JSON 对象。

收到的示例数据:将数据解码到下面给出的 CiItems 结构中

{
    "class_name": "test",
    "configuration_items": [
        {
            "id": "ea09a24f-01ef-42ad-ab19-e0369341d9b3",
            "ci_name": "makk",
            "comments": null,
            "created_by": "mike",
            "updated_by": "sam",
            "created": "2019-08-02T21:16:35.656Z",
            "updated": "2019-08-02T21:21:08.073Z",
            "ci_state_id": "randomid",
            "super_ci_id": null,
            "ci_attributes": [
                {
                    "attribute_id": "c995c693-b97c-4863-a61b-81a5d904c967",
                    "df_attribute_value": "xsmall",
                    "attribute_name": "tname",
                    "data_type": "string"
                },
                {
                    "attribute_id": "58845f48-7d2a-4c8c-8591-eaf59a23d84d",
                    "df_attribute_value": "vmware",
                    "attribute_name": "provider",
                    "data_type": "string"

                }
]}]}

下面是创建的结构:

 type Attribute struct {
    AttributeID      string `json:"attribute_id "`
    DfAttributeValue string `json:"df_attribute_value"`
    AttName          string `json:"attribute_name"`
    DataType         string `json:"data_type"`
}

// Attributes - array of Attribute
type Attributes []Attribute

// CiItem - confiuraion item of a VM
type CiItem struct {
    ID        string     `json:"ci_id"`
    Created   string     `json:"created"`
    Updated   string     `json:"updated"`
    CreatedBY string     `json:"created_by"`
    UpdatedBY string     `json:"updated_by"`
    Atts      Attributes `json:"ci_attributes"`
}

// CiItems - array of CiItem
type CiItems struct {
    ClassName string   `json:"class_name"`
    Items     []CiItem `json:"configuration_items"`
}

解码数据并创建提取的 Json 的代码:

func (client *Client) GetList() (CiItems, error) {
    var out CiItems
    err := client.doJsonRequest("GET",  &out)
    log.Info(out)
    if err != nil {
        return out, err
    }
    var output map[string]interface{}
    //parseMap(out.Items[0].(map[string]interface{}))
    extractBase(out.Items[0], &output)
    return out, nil
}


func extractBase(ci interface{}, output interface{}) {
    fields := reflect.TypeOf(ci)
    values := reflect.ValueOf(ci)
    num := fields.NumField()

    for i := 0; i < num; i++ {
        field := fields.Field(i)
        value := values.Field(i)

        if string(field.Name) != "Atts" {
            name := string(field.Name)
            output[name] = string(value)
        }
    }
}

我正在尝试创建一个键值为 id、ci_name、created_by、updated_by、attribute_name 的 JSON,如下所示

{
  "ci_name": "makk",
  "created_by": "mike",
  "updated_by": "sam",
  "created": "2019-08-02T21:16:35.656Z",
  "updated": "2019-08-02T21:21:08.073Z",
  "tname": "xsmall",
  "provider": "vmware"
}

我试过用reflect等方法

最佳答案

使用 CiItem 字段中的值创建 map 并从函数返回它。

func extractBase(ci *CiItem) map[string]interface{} {
    result := map[string]interface{}{
        "ci_name":    ci.Name,
        "created_by": ci.CreatedBY,
        "updated_by": ci.UpdatedBY,
        "created":    ci.Created,
        "updated":    ci.Updated,
    }
    for _, a := range ci.Atts {
        result[a.AttName] = a.DfAttributeValue
    }
    return result
}

关于json - 尝试解析 JSON 并创建提取的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532143/

有关json - 尝试解析 JSON 并创建提取的 JSON的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  7. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  8. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  9. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  10. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

随机推荐