Skip to content

json package does not handle nil values #400

Closed
@zombiezen

Description

@zombiezen
What steps will reproduce the problem?
1. Run this Go source code:

package main 
import 
( 
    "fmt"; 
    "json"; 
    "os"; 
) 
func main() 
{ 
    jsonData := make(map[string]interface{}); 
    jsonData["foo"] = "bar"; 
    jsonData["fail"] = nil; 
    err := json.Marshal(os.Stdout, jsonData); 
    if err != nil 
    { 
        fmt.Fprintf(os.Stderr, "Error while marshalling: %s\n", err); 
        os.Exit(1); 
    } 
    fmt.Printf("\n"); 
} 

2. *OR* Run this source code:

package main 
import 
( 
    "fmt"; 
    "json"; 
    "os"; 
) 
func main() 
{ 
    var jsonData interface{} = nil; 
    err := json.Marshal(os.Stdout, jsonData); 
    if err != nil 
    { 
        fmt.Fprintf(os.Stderr, "Error while marshalling: %s\n", err); 
        os.Exit(1); 
    } 
    fmt.Printf("\n"); 
} 

What is the expected output? What do you see instead?

I would expect the first case to print
`{"foo":"bar","fail":null}`, but it gives an error: `Error
while 
marshalling: json cannot encode value of type interface { }`

The second case should just print `null`, but it SEGSEGVs.

What is your $GOOS?  $GOARCH?

darwin amd64

Which revision are you using?  (hg identify)
c36376f7c054+ tip

Please provide any additional information below.

I originally reported this on the go-nuts mailing list:
http://groups.google.com/group/golang-
nuts/browse_thread/thread/4a7972add964dd7/feba4a6e90bcf1e0

I do have a patch for this, I will post it momentarily.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions