I've got two different json files and would like to merge them and read json strings from one file.
{"ipAddress":"1.1.1.1","port":80, "protocol":"http"}
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}
I tried something, but it still doesn't work properly. I tried array and also the following structure:
{"jsonString1": {"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
"jsonString2": {"ipAddress":"1.1.1.1", "domainName":"domain.com"}}
Not sure if the structure is correct. I just need to get "jsonString1", "jsonString2" separately so I don't need to use more json files.
Your 1st fragment is non standard (effectively, not JSON).
Your 2nd IS standard, but is an object, not an array.
If you want an array, use an array:
[{"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}]
Alternatively, if you want to use your 2nd version (which is an object), you can access the 2 "sub-objects" by keys: myObj.jsonString1, myObj.jsonString2. BTW, A better name would be "Obj1" & "Obj2" since these are not strings, they're actual objects.
Use JSON Array to keep those files merged.For example
Conside,You have an JSON array for URL then and you want to print it in a paragraph then
<p id="url"></p>
declare a variable like this
var URL=[{"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
{"ipAddress":"1.1.1.1", "domainName":"domain.com"}]
you can access these array by using
document.getElementById("url").innerHTML =
URL[0].ipAddress+ " " + URL[0].port+ " " +URL[0].protocol;
You can get the array values by using the index values
Thank you. I have finally used this syntax:
json:
{"jsonString1": {"ipAddress":"1.1.1.1","port":80, "protocol":"http"},
"jsonString2": {"ipAddress":"1.1.1.1", "domainName":"domain.com"}}
read the string using this command:
var jsonObject = JObject.Parse(jsonData);
string value = jsonObject["jsonString1"].ToString();
Related
I have a string in plain text which contains brackets like JSON format as it is created using JavaScriptSerializer().Serialize() method. I need to remove brackets and collon and want to convert it into key = value, key = value format.
Need to convert
{
"account":"rf750",
"type":null,
"amount":"31",
"auth_type":"5",
"balance":"2.95",
"card":"re0724"
}
to
'account=rf750,type=null,amount=31,authe=5,balanc=2.95,card=re0724'
Well, you've got three different things going on here.
The first, and surface issue, is: how do you change the string?
Simple - you do some string substitutions, preferably using Regex. Remove the starting/ending braces, change [a]:"[b]", to [a]=[b], - or however you want the final format to look like.
The second, and slightly deeper issue is: JSON isn't just a simple list of keys=values. You can have nesting. You can have non-string data. Simply saying you want to change the JSON result to key=value,key=value,key=value, etc - is fragile. How do you know the JSON structure will be what you're expecting? JSON Serialization will serialize successfully even if you've got nested structures, non string/int data, etc. And if you want solid code that doesn't easily break, you have to figure out: how do I handle this? Can I handle this?
The third, and final thing is: you're taking a standard data format schema and figuring out how to translate it to a nonstandard data format. 90% of the time someone does that, they deserve to be shot. Seriously, spend some solid time asking yourself whether you can use the JSON as-is, and whether the process wanting key=value,key=value,etc can be changed to use an actual standardized data format.
Here is simple solution which (1) parses json to Dictionary and (2) uses String.Join and Linq Select to provide desired output:
using System.Linq;
using Newtonsoft.Json;
..
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
var str = string.Join(',', dict.Select(r => $"{r.Key}={r.Value}"));
str-variable now contains:
account=rf750,type=,amount=31,auth_type=5,balance=2.95,card=re0724
Well thanks everyone for your time and response. your answer led me towards solution and finally i found the following solution which resolved the issue perfectly.
var jObj = (JObject)JsonConvert.DeserializeObject(modelString);
modelString = String.Join("&",jObj.Children().Cast<JProperty>().Select(jp => jp.Name + "="+ HttpUtility.UrlEncode(jp.Value.ToString())));
the above code converts the JSON into a url encoded string and remove the JSON format
I have a text something like this:
Text in pastebin.
altough my text will be significantly larger with multiple items. as you can see in the above text there is a textDisplay entry which will appear in every single item. is there a way to get the text inside the textDisplay "variable" from all items? I've tried with Json but had not luck. Also tried to get the text between textDisplay and the comma something like:
string data = getBetween(text, "textDisplay", ",");
but it only read the first one.
Thank you
If you want to get all data and map it to the models or only specific values, you should to use something like Newtonsoft.Json. See links below:
How to get some values from a JSON string in C#?
C# Parsing JSON array of objects
I hope it will help you to solve your problem.
EDIT
I've tried with Json but had not luck
Maybe problem is in JSON you try to parse? The block that you show is broken: it should be end with }]} to be valid: FIXED ONE.
So I'm working with umbraco and using the tag datatype. I'm trying to take all tags added to a given node and putting them into an array of strings but when I grab the value it always seems to come out like this:
"[\"Tag1\",\"Tag2\"]"
How can I convert this string of an array back into a regular array? All I have gotten so far was a string of individual characters
The array format you have provided as an example looks like part of the JSON object.
You could use JSON.net library to parse array token of the JSON object.
var array = JArray.Parse(tagString).Values<string>();
A complete example is available here.
You could try:
string[] newArray = item.Replace("\"", "").Replace("[", "").Replace("]", "").Split(',');
This would output as Tag1, Tag2 etc...
Hope this helps.
Use this
var tagString = "[\"Tag1\",\"Tag2\",\"Tag3\",\"Tag4\"]";
var tags = tagString.Trim().TrimStart('[').TrimEnd(']').Split(',');
I have trouble using Regex to split a text file of JSON objects into string. The array of JSON objects are downloaded from an url and is meant to be processed by some javascript function. But I want to read them in C#. I have downloaded the file and just need to split it into individual JSON objects. The format of the text file is:
{......},{"S":...}
So I want to split it into a string[] so each JSON object is a string:
{"S":...}
{"S":...}
{"S":...}
{"S":...}
I want to leave out the comma that separates them in the original text file.
string[] jsons = Regext.Split(txtfile, "\{\"S\":");
But this doesn't work. How can I split it correctly?
If you aren't aware already this is a great tool http://regexr.com?36u96
Try
string[] splits = Regex.Split(txtfile, #"(?<=\}),");
You can use the JsonTextReader class provided by the Newtonsoft.JSON assembly (acquirable through NuGet).
I'm using the ExportAPI from MailChimp. It sends back a "root"-less Json string like so:
["Email Address", "First Name", "Last Name"]
["jeff#mydomain.com", "Jeff", "Johnson"]
["tubbs#mydomain.com", "Tubbs", "McGraw"]
No brackets, nothing- just a couple of arrays. Loading it into a JArray only picks up the first object:
JArray jsonArray = new JArray.Parse(jsonResponse);
Console.WriteLine(jsonArray);
//Outputs:
//Email Address
//First Name
//Last Name
I'm hoping to copy the contents of the string into a database and need to access the response with LINQ. Any suggestions as to the correct way to work with a Json Object like I've shown above (using Json.net or otherwise?)
Pad the string with a root element, just add '[' and ']'?
This behavior is actually completely on purpose as mentioned in the docs. The reasoning is that a full dump of a list's data can easily be way too large to consistently fit it in memory and parse it. As such, and given the return format, you're expected to use a newline as the delimiter (or read it off the wire that way), parse each object individually, and then do whatever you need with them.
I am not familiar with doing that in C#/Linq, but the PHP example on the docs page does exactly that.