英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论