从JSON字符串中删除空数组成员 [英] Removing empty array members from a JSON string

查看:63
本文介绍了从JSON字符串中删除空数组成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串,如下所示.我想以编程方式从中删除空数组对象,以便可以将其转换为DataTable.

I have a JSON string as shown below. I want to remove the empty array objects from it programmatically so that I can convert it to a DataTable.

这是我的JSON的示例:

Here is an example of my JSON:

{
   "result":[
     {
       "id":"1",
       "name": "Temp",
       "property":[]
     },
     {
       "id":"2",
       "name": "Temp2",
       "property":[]
     }
  ]
}

您可以看到每个结果中的property成员是一个空数组.关于如何删除它的任何建议?

You can see that the property member in each result is an empty array. Any suggestion on how I can remove it?

当前,我正在执行以下操作以将JSON转换为DataTable:

Currently I'm doing the following to convert the JSON to a DataTable:

DataTable dt = JsonConvert.DeserializeObject<DataTable>(data["result"].ToString());

当我手动删除array属性时,转换效果很好.

When I manually remove the array property, the conversion works perfectly.

推荐答案

您可以使用正则表达式从json字符串本身中删除具有空数组的属性.这是一个使用两个正则表达式的控件,一个使用空数组杀死属性,另一个使用杀死所有剩余的错误逗号.

You could use a regex to remove the properties with empty arrays from the json string itself. Here is one that uses two regexes, one to kill the properties with empty arrays and the other to kill any erroneous commas that are left over.

var json = "{\"prop\": [], \"prop2\": \"test\", \"propqw\": []}";
var removeEmpty = new Regex("\\s*\"[^\"]+\":\\s*\\[\\]\\,?");
var removeComma = new Regex(",(?=\\s*})");
var result = removeEmpty.Replace(json, "");
result = removeComma.Replace(result, "");

可能有一种比这更干净的方法,但是我无法快速找到一种删除属性并清除潜在的非法逗号的正则表达式.

There may be a slightly cleaner way than this but I couldn't quickly find a single regex way to remove properties and clean potential illegal commas.

这篇关于从JSON字符串中删除空数组成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆