开发者

Remove empty {} in JSON

开发者 https://www.devze.com 2023-03-23 05:40 出处:网络
I have JSON which is something like this Var myObj = {{},{\'test\': \'1\'}} I would like to remove the {} so end up like

I have JSON which is something like this

Var myObj = {{},{'test': '1'}}

I would like to remove the {} so end up like

{'test':'1'}.  

How can do th开发者_如何学Gois?


This is totally not valid JSON. You'll get an error if you actually try to assign that not-JSON to a variable ("Var" should be lowercase by the way).

You'll need to convert it to a string (actually presumably it is a string already because it's invalid as an object), use a regex to replace the offending invalid JSON, and then convert back to JSON.

var myObjStr = "{{},{'test': '1'}}";
var validMyObjStr = myObjStr.replace(appropriateRegEx, '');
var myObj = eval('(' + validMyObjStr + ')');

If you need it, I can build an appropriate RegEx for you. Just drop a comment. But really, you should probably fix whatever's giving you the invalid JSON in the first place.

0

精彩评论

暂无评论...
验证码 换一张
取 消