doucheng1884
2015-12-14 18:45
浏览 127
已采纳

从(json)字符串中删除无效字符

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'
}]

图片转代码服务由CSDN问答提供 功能建议

我正在执行go程序中的命令,该命令为我提供了结构的一些输出 \ n

  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验证器中时,出现此错误

 错误: 在第1行上解析错误:
 [{
 --- ^ 
期望'STRING','}',得到了'undefined'
   
 
 

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

Update

this 是我的编码魔术产生的输出。 我不确定确切的部分是 invalid

  [{
'name':'Leroy',
'phone'  :'12345'
},
 {
'name':'Jimmy',
'phone':'23456'
}] 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doudang4568 2015-12-14 19:00
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题