Home > other >  Regex for replacing unnecessary quotation marks within a JSON object containing an array
Regex for replacing unnecessary quotation marks within a JSON object containing an array

Time:10-07

I am currently trying to format a JSON object using LabVIEW and have ran into the issue where it adds additional quotation marks invalidating my JSON formatting. I have not found a way around this so I thought just formatting the string manually would be enough.

Here is the JSON object that I have:

{
    "contentType":"application/json",
    "content":{
        "msgType":2,
        "objects":"["cat","dog","bird"]",
        "count":3
    }
}

Here is the JSON object I want with the quotation marks removed.

{
    "contentType":"application/json",
    "content":{
        "msgType":2,
        "objects":["cat","dog","bird"],
        "count":3
    }
}

I am still not an expert with regex and using a regex tester I was only able to grab the "objects" and "count" fields but I would still feel I would have to utilize substrings to remove the quotation marks.

Example I am using (would use a "count" to find the start of the next field and work backwards from there)

"([objects]*)"

Additionally, all the other Regex I have been looking at removes all instances of quotation marks whereas I only need a specific area trimmed. Thus, I feel that a specific regex replace would be a much more elegant solution.

If there is a better way to go about this I am happy to hear any suggestions!

CodePudding user response:

After using a regex from one of the comments, I ended up with this regex which allowed me to match the array itself.

(\[(?:"[^"]*"|[^"]) \])

I was able to split the the JSON string into before match, match and after match and removed the quotation marks from the end of 'before match' and start of 'after match' and concatenated the strings again to form a new output.

CodePudding user response:

Your question suggests that the built-in LabVIEW JSON tools are insufficient for your use case.

The built-in library converts LabVIEW clusters to JSON in a one-shot approach. Bundle all your data into a cluster and then convert it to JSON.

LabVIEW Built-in JSON functionality

When it comes to parsing JSON, you use the path input terminal and the default type terminals to control what data is parsed from a JSON string.

If you need to handle JSON in a manner similar to say JavaScript, I would recommend something like the An example of the JSONText toolkit

The Output controls from both my examples are identical - although JSONText provides a handy Pretty Print vi.

Front Panel from example code

  • Related