FAQ
I'm porting an app from PHP to GoLang. It takes JSON of any schema and does
some cool stuff. One of the things I'm having problems with is converting
the array_key_exists to Go to test an interface.

$json = json_decode($json_incoming);

if (array_key_exists($key, $json)) {


in golang I think it should be something like:

var json interface{}
json := json.unmarshal(json_incoming)

if _,ok := json[key]; ok {


but that doesn't work... Any ideas?

--

Search Discussions

  • Matt Kane's Brain at Dec 20, 2012 at 4:22 pm
    That's not the signature of json.Unmarshal, and giving a variable the same
    name as a package you're importing is dangerous.

    First, you need to pass the address of your interface{} variable, or
    json.Unmarshal() will not be able change it.

    var j interface{}
    json.Unmarshal(json_incoming, &j)

    Now, you need to do a type assertion:

    jmap := j.(map[string]interface{})
    if _, ok := jmap[key]; ok {
    // do stuff
    }

    On Thu, Dec 20, 2012 at 3:34 AM, wrote:

    var json interface{}
    json := json.unmarshal(json_incoming)

    if _,ok := json[key]; ok {

    --
    matt kane's brain
    http://hydrogenproject.com

    --
  • Kyle Lemons at Dec 20, 2012 at 5:43 pm
    If you know it will be an object (aka, {}) you can decode straight into a
    map[string]interface{}:
    http://play.golang.org/p/U0DNmOXPA4

    On Thu, Dec 20, 2012 at 11:22 AM, Matt Kane's Brain wrote:

    That's not the signature of json.Unmarshal, and giving a variable the same
    name as a package you're importing is dangerous.

    First, you need to pass the address of your interface{} variable, or
    json.Unmarshal() will not be able change it.

    var j interface{}
    json.Unmarshal(json_incoming, &j)

    Now, you need to do a type assertion:

    jmap := j.(map[string]interface{})
    if _, ok := jmap[key]; ok {
    // do stuff
    }

    On Thu, Dec 20, 2012 at 3:34 AM, wrote:

    var json interface{}
    json := json.unmarshal(json_incoming)

    if _,ok := json[key]; ok {

    --
    matt kane's brain
    http://hydrogenproject.com

    --

    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedDec 20, '12 at 4:10p
activeDec 20, '12 at 5:43p
posts3
users3
websitegolang.org

People

Translate

site design / logo © 2022 Grokbase