手动读取JSON值

在Go语言中,我通常将JSON解组为结构体并从该结构体中读取值。 / p>

这一次,我只关心JSON对象的某个元素,并且由于整个JSON对象非常大,因此我不想创建一个结构。</ p >

Go中有一种方法,这样我就可以照常使用键或迭代数组在JSON对象中查找值。</ p>

考虑以下JSON如何 我只拉出 title </ code>字段。</ p>

  {
“ title”:“发现了一个错误”,
“ body”:“我 '对此有问题。”,
“受让人”:“ octocat”,
“里程碑”:1,
“标签”:[
“ bug”
]
}
</ 代码> </ pre>
</ div>

展开原文

原文

In Go I usually unmarshal my JSON into a struct and read values from the struct.. it works very well.

This time around I am only concerned with a certain element of a JSON object and because the overall JSON object is very large, I don't want to have to create a struct.

Is there a way in Go so that I can lookup values in the JSON object using keys or iterate arrays as per usual.

Considering the following JSON how could I pull out the title field only.

{
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  "assignee": "octocat",
  "milestone": 1,
  "labels": [
    "bug"
  ]
}

donglun4682
donglun4682 好的,我认为它会抱怨字段不匹配。谢谢。
4 年多之前 回复
dongteng2534
dongteng2534 您可以为所需的零件专门制作一个结构。这来自Unmarshal()下的json包:“为了将JSON解组到结构中,Unmarshal将传入的对象键与Marshal使用的键(结构字段名称或其标签)进行匹配,希望使用完全匹配但还接受大小写的方式-不敏感的匹配。解组只会设置结构的导出字段。”如果该字段不存在,则应该将json键/值对简单地忽略。
4 年多之前 回复

5个回答

To extend Darigaaz's answer, you can also use an anonymous struct declared within the parsing function. This avoids having to have package-level type declarations litter the code for single-use cases.

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

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    test := `{
        "title": "Found a bug",
        "body": "I'm having a problem with this.",
        "assignee": "octocat",
        "milestone": 1,
        "labels": [
          "bug"
        ]
    }`

    var s struct {
        Title string `json:"title"`
    }
    json.Unmarshal([]byte(test), &s)

    fmt.Printf("%#v", s)

}

Dont declare fields you dont want.

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

package main

import (
    "fmt"
    "encoding/json"
)

type Struct struct {
    Title   string  `json:"title"`
}

func main() {
    test := `{
        "title": "Found a bug",
        "body": "I'm having a problem with this.",
        "assignee": "octocat",
        "milestone": 1,
        "labels": [
          "bug"
        ]
    }`

    var s Struct
    json.Unmarshal([]byte(test), &s)

    fmt.Printf("%#v", s)

}

Or if you want to completely get rid of structs:

var i interface{}
json.Unmarshal([]byte(test), &i)

fmt.Printf("%#v
", i)
fmt.Println(i.(map[string]interface{})["title"].(string))

Or. It will swallow all conversion errors.

m := make(map[string]string)

json.Unmarshal([]byte(test), interface{}(&m))

fmt.Printf("%#v
", m)
fmt.Println(m["title"])



签出 go -simplejson </ p>

示例:</ p>

  js,err:= simplejson.NewJson([] byte({
“ test”:{
“ string_array”:[“ asdf”,“ ghjk”,“ zxcv”],
“ string_array_null”:[“ abc”,null,“ efg”],
“ array”:[ 1,“ 2”,3],
“ arraywithsubs”:[{“ subkeyone”:1},
{“ subkeytwo”:2,“ subkeythree”:3}],
“ int”:10,\ n“ float”:5.150,
“ string”:“ simplejson”,
“ bool”:true,
“ sub_obj”:{“ a”:1}
}
}
)))
\ nif _,确定= js.CheckGet(“ test”); !ok {
//缺少测试结构
}

aws:= js.Get(“ test”)。Get(“ arraywithsubs”)
aws.GetIndex(0)
</ code> </ pre >
</ div>

展开原文

原文

Check out go-simplejson

Example:

js, err := simplejson.NewJson([]byte(`{
  "test": {
    "string_array": ["asdf", "ghjk", "zxcv"],
    "string_array_null": ["abc", null, "efg"],
    "array": [1, "2", 3],
    "arraywithsubs": [{"subkeyone": 1},
    {"subkeytwo": 2, "subkeythree": 3}],
    "int": 10,
    "float": 5.150,
    "string": "simplejson",
    "bool": true,
    "sub_obj": {"a": 1}
  }
}`))

if _, ok = js.CheckGet("test"); !ok {
  // Missing test struct
}

aws := js.Get("test").Get("arraywithsubs")
aws.GetIndex(0)

duanque3125
duanque3125 当然,这完全取决于您的需求。 例如,当我必须对JSON有效负载进行单元测试时,我特别喜欢这个库。 但是,不要为小任务添加第三方库的好习惯:)
4 年多之前 回复
douchuituo3032
douchuituo3032 谢谢,但是,恕我直言,这对于添加外部依赖关系来说是一个微不足道的问题。
4 年多之前 回复
package main

import (
    "encoding/json"
    "fmt"
)


type Seller struct {
  Name string
  ShareName string
  Holdings int
  Quantity int
  PerShare float64
}

type Buyer struct {
  Name string
  ShareName string
  Holdings int
  Quantity int
  PerShare float64

}
func validateTransaction(seller Seller,buyer Buyer) bool{         
    var isallowTransact bool =false
    if (seller.Quantity >=buyer.Quantity &&seller.PerShare == buyer.PerShare && seller.ShareName ==buyer.ShareName){
         isallowTransact=true; 
    }  

    return isallowTransact
    }

func executeTransaction(seller Seller,buyer Buyer) {         
       seller.Holdings -=seller.Quantity;
       buyer.Holdings +=seller.Quantity;
    fmt.Printf("seller current holding : %d, 
 buyyer current holding: %d",seller.Holdings,buyer.Holdings)

}

func main() {   
    sellerJson :=`{"name":"pavan","ShareName":"TCS","holdings":100,"quantity":30,"perShare":11.11}`
    buyerJson :=`{"name":"Raju","ShareName":"TCS","holdings":0,"quantity":30,"perShare":14.11}`
    var seller Seller 
    var buyer Buyer 
    json.Unmarshal([]byte(sellerJson ), &seller)
    json.Unmarshal([]byte(buyerJson ), &buyer)

    //fmt.Printf("seller name : %s, shares of firm: %s,total holdings: %d, want to sell: %d,unit cost: %f", seller.Name , seller.ShareName,seller.Holdings , seller.Quantity,seller.PerShare )
      var isallowExecute bool =false
    isallowExecute  =validateTransaction(seller,buyer)

    if(isallowExecute){ 
    executeTransaction(seller,buyer)
    }else{
     fmt.Print("
 seems buyer quotes are not matching with seller so we are not able to perform transacrion ,Please check and try again");

    }
    fmt.Println("
 Happy Trading...!!");

    }
doukuang1897
doukuang1897 嗨,虽然这段代码可以回答问题,但是提供有关如何和/或为什么解决问题的其他上下文将提高​​答案的长期价值。
一年多之前 回复



更新</ strong>:此答案是错误的; 我将其作为 not </ em>要做的一个示例。</ p>

您应该先使用正则表达式查找(伪代码):</ p> \ n

  String s = {json source}; 
int i = s.indexOf(“ \” title \“:\”“)
s.substring(i,s.indexOf(” \“ “,i))
</ code> </ pre>

有关Java子字符串的更多信息 </ p>
</ div>

展开原文

原文

Update: This answer is wrong; I'm leaving it as an example of what not to do.

You should look it up with a regex then (pseudocode):

String s = {json source};
int i = s.indexOf("\"title\": \"")
s.substring(i,s.indexOf("\"",i))

more on substrings in Java

douhan4243
douhan4243 哦,对不起。 我不会删除答案作为将来的榜样,但仍会冒着名誉的风险
4 年多之前 回复
dongliao6777
dongliao6777 通常,使用正则表达式解析“ json / html / xml”之类的“结构化”文本通常是个坏主意。 我举了一个例子。
4 年多之前 回复
duanmianhong4893
duanmianhong4893 ? 那是因为我过于复杂了一个简单的解决方案还是一线灵感?
4 年多之前 回复
douwei6478
douwei6478 {“ body”:“ \\ title \”:\“ pick me \”“,” title“:”如果可以的话,赶上我“}
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐