jjzjj

json - 在 golang json.Unmarshal 中处理单个或数组结构的好方法是什么?

coder 2024-07-11 原文

我正在使用 Go 和 Yahoo API 构建一个股票报价网络应用程序。

问题是如何在不编写另一个结构的情况下在数组和单个结构之间切换。我不确定如何用语言来解释它。 这是示例:

从 Yahoo API 获取一个符号引用如下所示:

{"query":{"count":1,"created":"2016-05-11T02:12:33Z","lang":"en-US","results":{"quote":{"Change":"+0.21","DaysLow":"9.32","DaysHigh":"9.68","Name":"Alcoa Inc. Common Stock","Open":"9.56","PreviousClose":"9.46","Symbol":"aa","Volume":"22266533","PercentChange":"+2.22%"}}}}

从 Yahoo API 获取多个引用:

{"query":{"count":2,"created":"2016-05-11T02:17:48Z","lang":"en-us","results":{"quote":[{"Change":"+0.21","DaysLow":"9.32","DaysHigh":"9.68","Name":"Alcoa Inc. Common Stock","Open":"9.56","PreviousClose":"9.46","Symbol":"aa","Volume":"22266533","PercentChange":"+2.22%"},{"Change":"+0.63","DaysLow":"92.11","DaysHigh":"93.57","Name":"Apple Inc.","Open":"93.35","PreviousClose":"92.79","Symbol":"aapl","Volume":"33686836","PercentChange":"+0.68%"}]}}}

区别在于引号变成了数组[]

使用json.Unmarshal(quoteResultRawJSON, &queryResult)时如何处理?

我的结构看起来像:

type QueryResult struct {
  Id bson.ObjectId `bson:"_id,omitempty"`
  Query Query `json:"query"`
}

type Query struct {
  Count int `json:"count"`
  Created string `json:"created"`
  Lang string `json:"lang"`
  Results Quote `json:"results"`
}

type Quote struct {
  Quote StockQuote `json:"quote"` //Here is the difference. Do I need to re-write the whole struct in order to handle []
}

type StockQuote struct {
  Change string `json:"change"`
  PercentChange string `json:"percentChange"`
  DaysLow string `json:"daysLow"`
  DaysHigh string `json:"daysHigh"`
  Open string `json:"open"`
  PreviousClose string `json:"previousClose"`
  Symbol string `json:"symbol"`
  Name string `json:"name"`
  Volume string `json:"volume"`
 }

我是否必须编写另一个结构来处理数组?

最佳答案

使用 UnmarshalJSON() 覆盖控制解码过程。

https://play.golang.org/p/pCSgymQYC3

package main

import (
    "log"
    "encoding/json"
    "bytes"
)

const(
    s1=`{"query":{"count":1,"created":"2016-05-11T02:12:33Z","lang":"en-US","results":{"quote":{"Change":"+0.21","DaysLow":"9.32","DaysHigh":"9.68","Name":"Alcoa Inc. Common Stock","Open":"9.56","PreviousClose":"9.46","Symbol":"aa","Volume":"22266533","PercentChange":"+2.22%"}}}}`
    s2=`{"query":{"count":2,"created":"2016-05-11T02:17:48Z","lang":"en-us","results":{"quote":[{"Change":"+0.21","DaysLow":"9.32","DaysHigh":"9.68","Name":"Alcoa Inc. Common Stock","Open":"9.56","PreviousClose":"9.46","Symbol":"aa","Volume":"22266533","PercentChange":"+2.22%"},{"Change":"+0.63","DaysLow":"92.11","DaysHigh":"93.57","Name":"Apple Inc.","Open":"93.35","PreviousClose":"92.79","Symbol":"aapl","Volume":"33686836","PercentChange":"+0.68%"}]}}}`
)
type QueryResult struct {
    //Id bson.ObjectId `bson:"_id,omitempty"`
    Query Query `json:"query"`
}

type Query struct {
    Count int `json:"count"`
    Created string `json:"created"`
    Lang string `json:"lang"`
    Results Quote `json:"results"`
}

type structOrArray struct{
    parent *Quote
    s StockQuote
    a []StockQuote
}

func (this *structOrArray)UnmarshalJSON(data []byte) error{
    d := json.NewDecoder(bytes.NewBuffer(data))
    t, err := d.Token();
    if err != nil{
        return err
    }
    if t==json.Delim('['){
        if err := json.Unmarshal(data, &this.a);err != nil {
            return err
        }
        return nil
    }
    if err := json.Unmarshal(data, &this.s);err != nil {
        return err
    }
    return nil
}

type fakeQuote struct{
    Load structOrArray `json:"quote"` //Here is the difference. Do I need to re-write the whole struct in order to handle []
}
type Quote struct {
    Quote *StockQuote
    Quotes []StockQuote
}
func (this *Quote)UnmarshalJSON(data []byte) error{
    fq := fakeQuote{}
    if err := json.Unmarshal(data, &fq);err != nil{
        return err
    }
    this.Quote = &fq.Load.s
    this.Quotes = fq.Load.a
    return nil
}
type StockQuote struct {
    Change string `json:"change"`
    PercentChange string `json:"percentChange"`
    DaysLow string `json:"daysLow"`
    DaysHigh string `json:"daysHigh"`
    Open string `json:"open"`
    PreviousClose string `json:"previousClose"`
    Symbol string `json:"symbol"`
    Name string `json:"name"`
    Volume string `json:"volume"`
}
func main() {
    r := QueryResult{}
    err := json.Unmarshal([]byte(s1), &r)
    if err != nil {
        log.Fatalln(err)
    }
    log.Println(r.Query.Results.Quote)
    log.Println(r.Query.Results.Quotes)

    err = json.Unmarshal([]byte(s2), &r)
    if err != nil {
        log.Fatalln(err)
    }
    log.Println(r.Query.Results.Quote)
    log.Println(r.Query.Results.Quotes)
}

关于json - 在 golang json.Unmarshal 中处理单个或数组结构的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37152092/

有关json - 在 golang json.Unmarshal 中处理单个或数组结构的好方法是什么?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  6. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  7. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  8. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  9. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  10. 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

随机推荐