doujiaohuo1096 2017-11-19 03:18
浏览 172
已采纳

Go中的php json_encode

in php I have this:

<?php
    $x = array(1,2,3,4);
    $y = json_encode($x);
    echo $y;
?>

which its result is:

[1,2,3,4]

in Go when i use json.Marshal() or jsonEncoder encode method the result is:

[1 2 3 4]

which is not equivalent as the json_encode() result in php and I can't decode it in php.

Is there anyway to reach [1, 2, 3, 4] encoded result in go? (which has "," separator between each items)

  • 写回答

1条回答 默认 最新

  • duanhai1455 2017-11-19 09:12
    关注

    When you use json.Marshal the result will be [1 2 3 4] but if you want to use your result as a string and send it to another place like redis , or print on the screen as a valid json, you should explicitly cast your result.

    Here are the incorrect and correct codes:

    package main
    
    import (
        "fmt"
        "encoding/json"
    )
    
    func main() {
        x := []int64{1, 2, 3, 4}
        y, err := json.Marshal(x)
        if err != nil {
            panic(err)
        }
        fmt.Println(y)
    }
    

    and the correct code is : package main

    import ( "fmt" "encoding/json" )

    func main() {
        x := []int64{1, 2, 3, 4}
        y, err := json.Marshal(x)
        if err != nil {
            panic(err)
        }
        fmt.Println(string(y))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了