jjzjj

jquery - 戈朗 : Nested XML to JSON

coder 2024-07-08 原文

你好 StackOverFLowers!!

我正在尝试弄清楚如何给定 XML 输入,然后使用 Golang 将其转换为 JSON。例如……

<version>0.1</version> <termsofService>http://www.wunderground.com/weather/api/d/terms.html</termsofService> <features> <feature>conditions</feature> </features>

会变成

"version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features": { "feature": "conditions" },

我得到了 versiontermsofservice正确,但我不知道如何返回嵌套的 features .这是我必须硬编码的东西吗?

代码:

    type reportType struct{
    Version xml.CharData        `xml:"version"`
    TermsOfService xml.CharData `xml:"termsofService"
    `
    Features xml.CharData       `xml:"features>feature"`
    Zip      xml.CharData       `xml:"current_observation>display_location>zip"`
    Problem myErrorType     `xml:"error"`
}
type myErrorType struct{
    TypeOfError xml.CharData `xml:"type"`
    Desciption xml.CharData `xml:"description"`
}
type reportTypeJson struct{
    Version        string  `json:"version"`;
    TermsOfService string `json:"termsofService"`;
    Features    string `json:"features feature" `;
    Zip           string `json:"current_observation > display_location > zip"`;
}
func main() {
    fmt.Println("data is from WeatherUnderground.")
    fmt.Println("https://www.wunderground.com/")
    var state, city string
    str1 := "What is your state?"
    str2 := "What is your city?"
    fmt.Println(str1)
    fmt.Scanf("%s", &state)
    fmt.Println(str2)
    fmt.Scanf("%s", &city)
    baseURL := "http://api.wunderground.com/api/";
    apiKey := "YouDontNeedToKnow"
    var query string

    //set up the query
    query = baseURL+apiKey +
    "/conditions/q/"+
    url.QueryEscape(state)+ "/"+
    url.QueryEscape(city)+ ".xml"
    fmt.Println("The escaped query: "+query)

    response, err := http.Get(query)
    doErr(err, "After the GET")
    var body []byte
    body, err = ioutil.ReadAll(response.Body)
    doErr(err, "After Readall")
    fmt.Println(body);
    fmt.Printf("The body: %s\n",body)

    //Unmarshalling
    var report reportType
    xml.Unmarshal(body, &report)
    fmt.Printf("The Report: %s\n", report)
    fmt.Printf("The description is [%s]\n",report.Problem.Desciption)

    //Now marshal the data out in JSON
    var data []byte
    var output reportTypeJson
    output.Version = string(report.Version);
    output.TermsOfService = string(report.TermsOfService)

    output.Features= string(report.Features)
    output.Zip=string(report.Zip)
    data,err = json.MarshalIndent(output,"","      ")
    doErr(err, "From marshalIndent")
    fmt.Printf("JSON output nicely formatted: \n%s\n",data)


}
func doErr( err error, message string){
    if err != nil{
        log.Panicf("ERROR: %s %s \n", message, err.Error())
    }


}

输出:

JSON output nicely formatted: { "version": "0.1", "termsofService": "http://www.wunderground.com/weather/api/d/terms.html", "features \u003e feature": "conditions", "current_observation \u003e display_location \u003e zip": "64068" }

感谢您的宝贵时间!

最佳答案

您没有获得所需的输出,因为您的 json 结构定义不正确。你有;

type reportTypeJson struct{
    Version        string  `json:"version"`;
    TermsOfService string `json:"termsofService"`;
    Features    string `json:"features feature" `;
    Zip           string `json:"current_observation > display_location > zip"`;
}

将特征表示为一个字符串,但它实际上是一个对象,可以是 map[string]string 或者它自己的结构,可以这样定义;

type Features struct {
     Feature string `json:"feature"`
}

鉴于字段名称是复数,我猜想它是一个集合,因此将您的结构更改为

type reportTypeJson struct{
    Version        string  `json:"version"`;
    TermsOfService string `json:"termsofService"`;
    Features    map[string]string `json:"features"`;
    Zip           string `json:"current_observation > display_location > zip"`;
}

可能是您正在寻找的。当然,这意味着你必须修改一些其他代码,这些代码将值从 xml 结构分配给 json 或其他任何东西,但我认为你可以自己解决这个问题:D

编辑:下面的部分是您将 xml 类型转换为 json 类型的地方(即分配 reportTypeJson 的实例并将 reportType 中的值分配给它,以便您可以在其上调用 json marshal 以生成输出) .假设您正在使用上面的 reportTypeJson 定义,其中 Features 作为 map[string]string 您只需修改一行您设置 output.Features 的位置。在下面的示例中,我使用“复合文字”语法进行内联。这允许您在为集合赋值的同时实例化/分配集合。

//Now marshal the data out in JSON
var data []byte
var output reportTypeJson
output.Version = string(report.Version);
output.TermsOfService = string(report.TermsOfService)

output.Features= map[string]string{"features":string(report.Features)} // allocate a map, add the 'features' value to it and assign it to output.Features
output.Zip=string(report.Zip)
data,err = json.MarshalIndent(output,"","      ")
doErr(err, "From marshalIndent")
fmt.Printf("JSON output nicely formatted: \n%s\n",data)

关于jquery - 戈朗 : Nested XML to JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37015366/

有关jquery - 戈朗 : Nested XML to JSON的更多相关文章

  1. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  2. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

  3. jquery - 如何在 rails 3.1 上安装 jQuery - 2

    我以为它已经安装了,但在我的gemfile中有gem"jquery-rails"但是在我的asset/javascripts文件夹中accounts.js.coffeeapplication.js都被注释掉了这是我的虚拟railsapplication但是在源代码中没有jQuery并且删除链接不起作用......任何想法都丢失了 最佳答案 看看thisRailscast.您可能需要检查application.js文件并确保它包含以下语句。//=requirejquery//=requirejquery_ujs

  4. jquery - Rails 如何创建 Jquery flash 消息而不是默认的 Rails 消息 - 2

    我想在页面顶部创建自定义Jquery消息而不是标准RailsFlash消息。我想在我的投票底部附近创建一条即时消息。我的Controller:defvote_up@post=Post.find(params[:id])current_user.up_vote(@post)flash[:message]='Thanksforvoting!'redirect_to(root_path,:notice=>'Takforditindlæg,deternuonline!')rescueMakeVoteable::Exceptions::AlreadyVotedErrorflash[:error]

  5. javascript - jQuery 的 jquery-1.10.2.min.map 正在触发 404(未找到) - 2

    我看到有关未找到文件min.map的错误消息:GETjQuery'sjquery-1.10.2.min.mapistriggeringa404(NotFound)截图这是从哪里来的? 最佳答案 如果ChromeDevTools报告.map文件的404(可能是jquery-1.10.2.min.map、jquery.min.map或jquery-2.0.3.min.map,但任何事情都可能发生)首先要知道的是,这仅在使用DevTools时才会请求。您的用户不会遇到此404。现在您可以修复此问题或禁用sourcemap功能。修复:获取文

  6. jquery - 在 Rails 中从原型(prototype)切换到 jquery,助手呢? - 2

    我目前从prototype切换到jquery主要是为了支持简单的ajax文件上传。我使用:https://github.com/indirect/jquery-rails95%的javascript代码是由railshelper编写的,例如:-remote_function-render:updatedo|page|-page.replace_html'id',:partial=>'content'-page['form']['name']=something-page.visual_effect:highlight,'head_success'...我知道我必须为Jquery重写5%

  7. jquery - Ruby 1.9.1、Rails 2.3.2 和 jrails 0.4 出现 "rescue in const_missing"错误 - 2

    我最近开始了一个项目,团队决定我们希望使用jQuery而不是Prototype/Scriptaculous来满足我们的javascript需求。我们设置了我们的项目,并开始切换。插件已安装viatheseinstructions,一切都按计划进行。不久之后,当尝试运行“./script/server”时,我们收到以下错误:=>Rails2.3.2applicationstartingonhttp://0.0.0.0:3000/usr/local/lib/ruby/gems/1.9.1/gems/activesupport-2.3.2/lib/active_support/depende

  8. jquery - 使用 Rails 3 学习 Ajax 的资源 - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭10年前。有没有学习Ajax(jQuery)和Rails3的好资源?

  9. jquery - Sprockets::FileNotFound - 找不到文件 'jquery.ui' - 2

    这个问题已经被问过几次了,但我尝试了提供的解决方案,但仍然没有帮助,所以我提出了一个新问题。gem文件gem'jquery-ui-rails'按照建议,我将gem放在:assets组之外Application.css~*=require_self*=requirejquery.ui*=requirebootstrap-datepicker*=requirejquery.timepicker*=require_tree.*/RailsAssetPipeline根据列出的顺序加载Assets。在这里,我把它排在列表的第2位。Application.css.scss*=require_sel

  10. jquery - 'jquery-rails' 和 'jquery-ui-rails' 可以在一个项目下管理吗? - 2

    我有一个Rails应用,使用Rails5.1.6和ruby2.3.5p376我的Gemfile中有这两个gemgem'jquery-rails','~>4.3.3'gem'jquery-ui-rails','~>6.0.1'在show.html.erb中我有以下内容:$(function(){$("#datepicker").datepicker();});Date:在application.js中//=requirejquery-ui//=requirejquery//=requirerails-ujs//=requireturbolinks//=require_tree.在appl

随机推荐