解析一种JSON的字符串

时间:2017-01-20 17:44:11

标签: json regex

我有一组JSONish的字符串,但完全不符合JSON。它也是一种CSV,但值本身有时会有逗号。

字符串看起来像这样:

ATTRIBUTE:此属性的值,ATTRIBUTE2:另一个值,但是这个值中有一个逗号,ATTRIBUTE3:,另一个值......

我能看到的唯一两种模式主要是属性名称是大写字母,后跟一个:和空格。在第一个属性之后,模式是name-in-caps:space。

数据存储在Redshift中,所以我会看看是否可以使用正则表达式解决这个问题,但我的正则表达式知识是有限的 - 我会从哪里开始?

如果没有,我将采用python黑客攻击。

2 个答案:

答案 0 :(得分:0)

您所描述的内容将是:

^([A-Z\d]+?): (.*?), ([A-Z\d]+?): (.*?), ([A-Z\d]+?): (.*)$

虽然这个答案意味着你的第三个属性值并不真正以逗号开头,并且你的属性名称可以计算数字。

如果我们采用这个方法:

  • [A-Z\d]大写字母和数字
  • +?:尽可能多,直到第一个:
  • (.*?),一个空间,然后需要多个字符,直到昏迷空间
  • ^$字符串的开头和结尾分别为

其余的是重复这种模式。

( )只是为了识别您的捕获部分,在这种情况下,它们不会直接影响匹配。

Here's a working example

答案 1 :(得分:0)

正常情况下,正则表达式通常不适合使用。

阅读这篇深思熟虑的帖子了解详情:https://softwareengineering.stackexchange.com/questions/223634/what-is-meant-by-now-you-have-two-problems

当一个更简单的方案可以使用时,请使用它!这里有一个方案可以成功地解析结构,只要冒号只出现在属性和值之间,而不是在它们之间:

<强>代码

static void Main(string[] args)
{
    string data = "ATTRIBUTE: Value of this attribute,ATTRIBUTE2: Another value, but this one has a comma in it,ATTRIBUTE3:, another value,value1,ATTRIBUTE4:end of file";


    Console.WriteLine();
    Console.WriteLine("As an String");
    Console.WriteLine();

    Console.WriteLine(data);

    string[] arr = data.Split(new[] { ":" }, StringSplitOptions.None);

    Dictionary<string, string> attributeNameToValue = new Dictionary<string, string>();

    Console.WriteLine();
    Console.WriteLine("As an Array Split on ':'");
    Console.WriteLine();

    Console.WriteLine("{\"" + String.Join("\",\"", arr) + "\"}");

    string currentAttribute = null;
    string currentValue = null;

    for (int i = 0; i < arr.Length; i++)
    {
        if (i == 0)
        {
            // The first element only has the first attribute name
            currentAttribute = arr[i].Trim();
        }
        else if (i == arr.Length - 1)
        {
            // The last element only has the final value
            attributeNameToValue[currentAttribute] = arr[i].Trim();
        }
        else
        {
            int indexOfLastComma = arr[i].LastIndexOf(",");
            currentValue = arr[i].Substring(0, indexOfLastComma).Trim();
            string nextAttribute = arr[i].Substring(indexOfLastComma + 1).Trim();

            attributeNameToValue[currentAttribute] = currentValue;

            currentAttribute = nextAttribute;
        }
    }

    Console.WriteLine();
    Console.WriteLine("As a Dictionary");
    Console.WriteLine();

    foreach (string key in attributeNameToValue.Keys)
    {
        Console.WriteLine(key + " : " + attributeNameToValue[key]);
    }
}

<强>输出:

  

作为字符串

     

ATTRIBUTE:此属性的值,ATTRIBUTE2:另一个值,但是这个值中有一个逗号,ATTRIBUTE3:,另一个值,value1,ATTRIBUTE4:文件结尾

     

作为':'

上的数组分割      

{“ATTRIBUTE”,“此属性的值,ATTRIBUTE2”,“另一个值,但此处有一个逗号,ATTRIBUTE3”,“,另一个值,value1,ATTRIBUTE4”,“文件结尾”} < / p>      

作为词典

     

ATTRIBUTE:此属性的值

     

ATTRIBUTE2:另一个值,但是这个值中有一个逗号

     

ATTRIBUTE3:,另一个值,value1

     

ATTRIBUTE4:文件结尾