Simply Beautify a JSON in C# [duplicate] - c#

This question already has answers here:
JSON formatter in C#?
(18 answers)
Closed 3 years ago.
I've searched for a simple native way to beautify a JSON in C# and have fond none, so I did my own and share it here, hope it helps ;)
It transforms condensed JSON like this:
[{"level":1,"exp":110,"energyGranted":5,"itemGranted":null},{"level":2,"exp":195,"energyGranted":5,"itemGranted":null},{"level":3,"exp":296,"energyGranted":5,"itemGranted":null}]
To nice formated JSON like this:
[
{
"level": 1,
"exp": 110,
"energyGranted": 5,
"itemGranted": null
},
{
"level": 2,
"exp": 195,
"energyGranted": 5,
"itemGranted": null
},
{
"level": 3,
"exp": 296,
"energyGranted": 5,
"itemGranted": null
}
]
Context : I was working on a Unity project that handles JSON responses I get from a backend. I didn't want to append some third party C# library just for that simple task.
There is the JsonUtility.ToJson(obj, prettyPrint) Unity built-in method doing that but only from an object, not a JSON, thus my need.

Have you tried converting your string to object then then use ToJson function?
var myObj = JsonUtility.FromJson<YourClass>(jsonString);
var prettyString = JsonUtility.ToJson(myObj);

So here is my solution, it uses Regex groups to split the JSON in multiple lines and depending on the group modifies the indent.
To avoid complicating the regex I'm not dealing with spaces, so it expects a condensed JSON.
using System.Text; // used for StringBuilder, a better string concatenation than myStr += "content"
using System.Text.RegularExpressions;
public static class JsonUtil
{
public static string Beautify(string json)
{
const int indentWidth = 4;
const string pattern = "(?>([{\\[][}\\]],?)|([{\\[])|([}\\]],?)|([^{}:]+:)([^{}\\[\\],]*(?>([{\\[])|,)?)|([^{}\\[\\],]+,?))";
var match = Regex.Match(json, pattern);
var beautified = new StringBuilder();
var indent = 0;
while (match.Success)
{
if (match.Groups[3].Length > 0)
indent--;
beautified.AppendLine(
new string(' ', indent * indentWidth) +
(match.Groups[4].Length > 0
? match.Groups[4].Value + " " + match.Groups[5].Value
: (match.Groups[7].Length > 0 ? match.Groups[7].Value : match.Value))
);
if (match.Groups[2].Length > 0 || match.Groups[6].Length > 0)
indent++;
match = match.NextMatch();
}
return beautified.ToString();
}
}
To use it: var beautifiedJson = JsonUtil.Beautify(json);
It may not be the best solution in terms of performance but it worked perfectly for my use ^^
If you have a better one please take the time to share it ;)

Related

Newtonsoft.Json.JsonReaderException: Invalid JavaScript property identifier character: ,

I have this code
var list = new List<long>();
long id = 202;
list.Add(2000);
list.Add(2001);
list.Add(2002);
var stringOfIds = string.Join(",", list);
var paramList = #"{'ProjectId':" + id + ", 'EntityIDsList': " + stringOfIds + "}";
Console.WriteLine(paramList);
var parameters = JsonConvert.DeserializeObject<Dictionary<string, object>>(paramList);
Console.WriteLine(parameters);
for some particular reason, it doesn't Deserialize the object and it crashes. What I'm trying here to do is: transform a list of longs into a string, comma separated -> construct the paramList string and then deserialize it using Newtonsoft.Json. I believe that the error is somewhere in the stringOfIds but couldn't figure it out sadly. Do you know what am I doing wrong and how can I fix it?
Right now your paramList looks like this:
{
"ProjectId": 202,
"EntityIDsList":
2000,
2001,
2002
}
Which is not proper JSON. It should look like this:
{
"ProjectId": 202,
"EntityIDsList": [
2000,
2001,
2002
]
}
So you should change it to:
var paramList = #"{'ProjectId':" + id + ", 'EntityIDsList': [" + stringOfIds + "]}";
Also at this point Console.WriteLine(parameters); won't tell you anything meaningfull, you should probably change it to Console.WriteLine(parameters.ToString());
The string you have, paramList is not a valid JSON. JSON object has keys (and values if they are strings) surrounded with double quotes, not single quotes.
Corrected string with escaped double quotes:
#"{""ProjectId"": " + id + #", ""EntityIDsList"": """ + stringOfIds + #"""}";
If your purpose of writing this string is to convert it to an object, you should directly create an object. Also note that you cant print the objects with Console.WriteLine... you will need to convert this to a string first (JsonConvert.SerializeObject) then print it.
var parameters = new
{
ProjectId = id,
EntityIDsList = stringOfIds
};
Console.WriteLine(JsonConvert.SerializeObject(parameters, Formatting.Indented));
// output:
{
"ProjectId": 202,
"EntityIDsList": "2000,2001,2002"
}
If you want EntityIDList as a list of numbers, change the value of EntityIDsList to list instead of stringOfIds.
var parameters2 = new
{
ProjectId = id,
EntityIDsList = list
};
Console.WriteLine(JsonConvert.SerializeObject(parameters2, Formatting.Indented));
//output:
{
"ProjectId": 202,
"EntityIDsList": [
2000,
2001,
2002
]
}
You have two "problems"
you need to add extra single-quotes around the stringOfIds bit
maybe it's actually what you want, but... this will give you a dictionary with 2 items with keys: "ProjectId" and "EnitityIDsList".
As the list is stringified you may as well use D<string, string> (or dynamic, depending on what you're actually trying to do.
I'm guessing you will want to have a collection of "projects"? So the structure in the question won't work.
[
{ "1": "1001,1002" },
{ "2": "2001,2002" }
]
is the normal json form for a dictionary of items
[
{ "1": [1001,1002] },
{ "2": [2001,2002] }
]
into a D<string,List<int>> would be "better".
Strongly suggest you create classes/records to represent the shapes and serialize those. Rather than string concatenation. If you must, then try to use StringBuilder.
Also, although Newtonsoft will handle single quotes, they're not actually part of the spec. You should escape double-quotes into the string if you actually need to generate json this way.
Maybe this is just a cutdown snippet to demo your actual problem and I'm just stating the obvious :D
Just a load of observations.
The extra quotes is the actual "problem" with your sample code.

How to split a string into substrings and store into a List - c#

I need to split a string into multiple substrings and store those substrings into a list.
Here is an example of the possible contents stored in my initial string:
"{"Stocks": [{"APPLE-775121": false, "AMZN-007612": true, "GOLD-847571": true}]}"
The initial string is ever changing, their could be multiple stocks names in there. I need to extract these items only and store into a list of strings:
APPLE-775121
AMZN-007612
GOLD-847571
Having a little trouble parsing the string, I'm new to C# and don't know about all the useful string functions that exist.
So far what I have done is parsed the InitialString to a new string (named ParsedString) which contains:
"APPLE-775121": false, "AMZN-007612": true, "GOLD-847571": true
Can I get some help parsing the rest of this string and storing the substrings into a list?
Thanks in advance!
You will first want to create a class to house that Stock data. From there, you can use Newtonsoft's Json conversion utilities and LINQ to extract your list. I forget which, but some project templates actually come with the Newtonsoft package already installed, but if it's not there by default, you can get it here.
void Main()
{
var str = "{\"Stocks\": [{\"APPLE-775121\": false, \"AMZN-007612\": true, \"GOLD-847571\": true}]}";
var obj = JsonConvert.DeserializeObject<StockContainer>(str);
var stockList = obj.Stocks.SelectMany(dictEntry => dictEntry.Keys).ToList();
Console.Write(stockList); //this is what you want
}
public class StockContainer
{
public List<Dictionary<string, bool>> Stocks {get;set;}
}
If you are sure, that list always be wrapped in [ and ], and items' names won't contain any [, ], {, } and , you can use simple string.Split:
var str = "{\"Stocks\": [{\"APPLE-775121\": false, \"AMZN-007612\": true, \"GOLD-847571\": true}]}";
var listOfItems = str.Split(new char[] { '[', ']', '}', '{' }, StringSplitOptions.RemoveEmptyEntries)[1];
var extractedItems = listOfItems.Split(',').Select(item => item.Split(':')[0]).ToArray();

how to get the following data from a string [duplicate]

This question already has answers here:
Get Substring - everything before certain char
(9 answers)
Closed 6 years ago.
I am using C#
I got a string which looks something like this :
myString = "User1:John&User2:Bob'More text"
I used
var parsed = HttpUtility.ParseQueryString(myString);
and then i use parsed["User1"] and parsed["User2"] to get the data.
My problem is that parsed["User2"] returns me not only the name but also everything that comes after it.
I thought maybe to then seperate by the char '
But i not sure how to do it since it has a specific behaviour in Visual studio.
I thought about something like this?
private static string seperateStringByChar(string text)
{
int indexOfChar = text.IndexOf(');
if (indexOfChar > 0)
{
return text.Substring(0, indexOfChar);
}
else
{
return "";
}
}
This worked for me as Wiktor suggested.
if (s.IndexOf("'") > -1) { return text.Substring(0, text.IndexOf("'")); } else { return string.Empty; }
A clean way of doing it is by splitting the string besides the index of the ' and then getting the substring.
var splittedText = text.Split('\'');
Then you can separate it further. e.g
var splittedText2 = splittedtText[0].Split('\&');
var User1 = splittedText2[0].Split(':')[1];
var User2 = splittedText2[1].Split(':')[1];
Let's sum up the splitting.
var users=myString.Split('\'');
var john = users.Split('&')[0].Split(':')[1];
var bob = users.Split('&')[1].Split(':')[1];

Find string between brackets

I'm having a string that could look like this:
{
"acl_gent": {
"cluster": [],
"indices": [{
"names": ["am*"],
"privileges": ["read", "view_index_metadata"],
"query": "{\"match\": {\"ACL\": \"acl_gent\"}}"
}],
"run_as": []
},
"acl_luik": {
"cluster": [],
"indices": [{
"names": ["am*"],
"privileges": ["read", "view_index_metadata"],
"query": "{\"match\": {\"ACL\": \"acl_luik\"}}"
}],
"run_as": []
}
}
and I would like to split it up in to 2 strings, 1 containing the acl_gent and one conaining acl_luik
the string above can contain more then 2 acl's (and I DON'T know what the name will be)
so I started removing the first and last bracketes :
input = input.Substring(1, input.Length - 2);
but then I can't figure out on how to find the right closing bracket to extract the data.
this was the closest I got
private int closer(string input) {
var i = input.IndexOf('}');
Console.WriteLine(string.Format("[DEBUG] Checking: {0}", input.Substring(0, i).Contains('{')));
if (input.Substring(0, i).Contains('{')) {
return i + closer(input.Substring(i)) + 2;
}
return i;
}
What you have there is a JSON string, a common response from a web service, and there are plenty of libraries to parse JSON, the most common one being JSON.NET. With this you could do something like
JObject myJsonObject = JObject.Parse(myResponse)
and retrieve your strings by their key names, such as
JObject aclString = myJsonObject["acl_luik"];
There are plenty of resources online for parsing JSON strings if you wish to go into more detail.
You have 2 options here:
1) Parse as JSON and get the first 2 objects, this is the better one.
2) Parse using Stack as string of tokens to get what you want, like this:
- Remove the first and last { }
- Using stack, add all { you find, and once you find } remove the first { in the stack.
- Once the stack is empty then you get 1 complete object there, save the indeces while you work and it should be easy to substring with start and end.
I ran into the same problem recently. My solution was to deserialize the string to a json object (in my case a JObject using Json.net) and then accessing the individual members and serializing them to separate strings.
using Newtonsoft.Json.Linq;
public void MakeStrings(string json)
{
var jobject = JsonConvert.DeserializeObject<JObject>(json);
string acl_gent = JsonConvert.SerializeObject(jobject["acl_gent"]);
string acl_luik = JsonConvert.SerializeObject(jobject["acl_luik"]);
}

how to normalise json from javascript in c#

hello there i have this following j.s .. i am sending an array to my C# file in r in json format
var r=['maths','computer','physics']
$.post("Global.aspx", { opt: "postpost", post: w.val(),tags:JSON.stringify(r)
}, function (d) {
});
but in c# i am getting this type of string:
["Maths""Computer""Physics"]
.
i want only the words maths,computer,physics not the [ sign and " sign .. please help me out
i have following c# code :
string[] _tags = Request.Form["tags"].ToString().Split(',');
string asd="";
foreach (string ad in _tags) {
asd += ad;
}
You're looking for JSON deserialization:
List<string> list = new JavaScriptSerializer().Deserialize<List<string>>(Request.Form["tags"]);
As pointed out, you've split your string on the , character leaving you with an array of:
[0] = "[\"Maths\""
[1] = "\"Computer\""
[2] = "\"Physics\"]"
Because JSON is a data type, those square brackets actually have functional meaning. They're not just useless extra characters. As such, you need to parse the data into a format you can actually work that.

Categories