从(JSON)字符串中删除无效字符。

huangapple go评论66阅读模式
英文:

removing invalid characters from (json) string

问题

我正在执行一个在Go程序中的命令,它会给我一些结构化的输出。

c := exec.Command("mycommand")
stdout, _ := c.Output()

输出结果如下:

{
 'name': 'mike',
 'phone': '12345'
},
{
 'name': 'jim',
 'phone': '1234'
}

为了生成有效的JSON,我尝试在字符串前面添加[,在字符串后面添加],最后移除最后一个逗号。

k := "["
mystring := string(stdout)
k += mystring
k += "]"
str := strings.Replace(k, "},]", "}]",-1)

w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintf(w, str)

当我将最终结果放入JSON验证器时,出现以下错误:

Error: Parse error on line 1:
[{	
---^
Expecting 'STRING', '}', got 'undefined'

问题:有没有办法在字符串上执行json.Compact或类似的操作,或者在这种情况下如何生成有效的JSON?

更新:

这是我的代码生成的输出结果。我不确定哪一部分是无效的。

[{
  'name': 'Leroy',
  'phone': '12345'
},
{
  'name': 'Jimmy',
  'phone': '23456'
}]
英文:

I'm am executing a command in a go program which gives me some output with the structure

  c := exec.Command("mycommand")
  stdout, _ := c.Output()

Output

{
 'name': 'mike',
 'phone': '12345'
},
{
 'name': 'jim',
 'phone': '1234'
}, //notice the final comma

To make valid json, I am trying to prepend [ and then append ], and, finally, remove the final comma.

k := "["
mystring := string(stdout)
k += mystring
k += "]"
str := strings.Replace(k, "},]", "}]", -1)

w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintf(w, str)

When I put the final product in a json validator, I get this error

Error: Parse error on line 1:
[{	
---^
Expecting 'STRING', '}', got 'undefined'

Question: is there a way to do json.Compact or something similar on a string, or how can I make valid json in this situation?

Update

this is the output that my coding magic produces. I'm not sure exactly what part of it is invalid

[{
  'name': 'Leroy',
  'phone': '12345'
},
{
  'name': 'Jimmy',
  'phone': '23456'
}]

答案1

得分: 1

正如JimB在评论中指出的,单引号不是有效的JSON格式。所以,如果你运行另一个字符串替换k = strings.Replace(k, `'`, `"`, -1)来生成以下内容:

[{
    "name": "Leroy",
    "phone": "12345"
}, {
    "name": "Jimmy",
    "phone": "23456"
}]

那么它应该按照你的期望工作。

英文:

As JimB pointed out in comments single quotes are not valid json. So if you run another string replace k = strings.Replace(k, `'`, `"`, -1) to produce this;

[{
	"name": "Leroy",
	"phone": "12345"
}, {
	"name": "Jimmy",
	"phone": "23456"
}]

Then it should work as you expect.

huangapple
  • 本文由 发表于 2015年12月15日 02:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/34274351.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定