手动读取JSON值

时间:2016-06-07 13:55:07

标签: json go

在Go中,我通常将我的JSON解组成结构并从结构中读取值。它运行良好。

这一次,我只关心JSON对象的某个元素,因为整个JSON对象非常大,我不想创建一个结构。

Go中是否有一种方法可以使用键或迭代数组按常规方式在JSON对象中查找值。

考虑以下JSON,我怎么才能拔出title字段。

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

5 个答案:

答案 0 :(得分:7)

不要声明你不想要的字段。

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)

}

或者如果你想彻底摆脱结构:

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

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

或者。它会吞下所有转换错误。

m := make(map[string]string)

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

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

答案 1 :(得分:1)

要扩展Darigaaz的答案,您还可以使用在解析函数中声明的匿名结构。这避免了必须使用包级别类型声明来丢弃单用例的代码。

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)

}

答案 2 :(得分:0)

查看go-simplejson

示例:

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)

答案 3 :(得分:0)

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, \n 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("\n seems buyer quotes are not matching with seller so we are not able to perform transacrion ,Please check and try again");

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

    }

答案 4 :(得分:-3)

更新:这个答案错了​​;我将其作为的例子。

你应该用正则表达式(伪代码)查找它:

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

more on substrings in Java