Parsing a JSON string in C# like javascript or python do - javascript

I am trying to make a program that needs to read JSON data from a give file. But the JSON files may be very complex. Here is the code i am using
static void Main(string[] args)
{
//step one: get a correct file path
string filepath = getFilePath("Please write here the path to your file");
//getFilePath is just a function I wrote to read user entry and automatically sanitize the string.
while (!File.Exists(filepath)) { filepath = getFilePath("The file path appears to be wrong, please correct."); }
//Setep 2: read the text of the file
string fileJSONString = File.ReadAllText(filepath);
//step 3: parse
object myDictionaryFromJSON = (new JavaScriptSerializer().DeserializeObject(fileJSONString));
object question1 = myDictionaryFromJSON.questions[0];
}
The thing is that Visual Studio gives me a lot of erros. I have tried using Dictionary instead of object, but it still doesnt work the way I need it to work. For example, this would actually work on python.
myDictionaryFromJSON = json.loads(JSONtext);
question1 = myDictionaryFromJSON['questions'][0];
question1text = question1["theQuestion"];
question1options = question1["options"];
question1correctAnswer = question1["correctAnswer"];
This is just an example. The thing is that Python and javascript can work with json perfectly, and are really good at converting JSON strings to dictionaries and objects. But C# is not working. I don't know what to do. What could I do?

I am assuming you are not using Json.NET. If this the case, then you should try it.
It has the following features:
LINQ to JSON
The JsonSerializer for quickly converting your .NET objects to JSON
and back again
Json.NET can optionally produce well formatted, indented JSON for
debugging or display
Look how fast Json.NET compared to JavaScriptSerializer:http://i.stack.imgur.com/T77y2.png
Example code for load json file in C#:
JObject o1 = JObject.Parse(File.ReadAllText(#"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(#"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
}

Related

How to read an external JSON file as a string in javascript?

I have an external json file which I am using to initialize a js object in a web app (using webpack).
To read the file im doing this:
var myObject = require('json-loader!constants/myfile.json')
The application needs to modify the object over time and occasionally needs to return to the original state. Due to this, I've found this to be the most performant way to initialize and reinitialize (deep clone) the object:
var clonedObject = JSON.parse(JSON.stringify(myObject))
This approach seems redundant - First load a json object then stringify the object only to load it again.
Is there a way to read the JSON file as a string and then JSON.parse the object (thus omitting the JSON.stringify step)?
You can use raw-loader to read a file as string:
var jsonString = require('raw-loader!constants/myfile.json');
var obj1 = JSON.parse(jsonString);
var obj2 = JSON.parse(jsonString);
You'll want to read the file contents first using a blob perhaps.
Get the text content, then use the JSON.parse(jsonString).
Honestly I am too ignorant to keep libraries in my head, and thus I read JSON files with fs like this:
var fs=require("fs");
var stuff=JSON.parse(fs.readFileSync("filename","utf8"));
And then it is pretty sure that someone could store the intermediate result of fs.readFileSync() if they wanted to:
var fs=require("fs");
var originaljson=fs.readFileSync("filename","utf8");
var stuff=JSON.parse(originaljson);

How to convert a string from a file to an object with JS in .HTA without JSON.parse

I have a .HTA file with JS like this:
<script>
var fso = new ActiveXObject('Scripting.FileSystemObject');
var configsHandle = fso.OpenTextFile('configs.json', 1);
var configs = configsHandle.ReadAll();
configsHandle.Close();
alert(configs);
</script>
and my configs.json is
{"default":{"content":"main"}}
I can successfully get content of the json file as a string. But I can't convert it to JSON with JSON.stringify() and then to parse it with JSON.parse() because I get the error
JSON is undefined
and I don't know how to convert the string to an object / array and then to parse it at least as an associative array with
alert(configs['default']['content']);
ps. I need it to be working on Microsoft HTML Apllication host program of Win7 (i.e. not in Chrome and not in Linux or other OS)

Escaping the whole object array with JQuery

Can I escape array of object with Jquery ? I got error SyntaxError: illegal character when I retrieving Java.Util.List object. At my Controller class , I pass object array as like that..
Map<String, List<User>> result = new HashMap<String, List<User>>();
// getting datas from database
List<User> datas = new ArrayList<User>();
datas = dao.get...................
result.put("data",datas);
When I gettting it from my JSP as
<script type="text/javascript">var results = ${result.data};</script>
I got syntaxError.So, I googling it and I assume my object array contains illegal characters and I should escape them. (This may my opinion ). So , I tried to escape charaters of this object array but I don't know how to do it ? I tried as like these..
console.log(JSON.stringify(${result.data}));
console.log(${result.data}.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'));
console.log(${result.data}.replace(/[\u0021-\u002f\u003a-\u0040\u005b-\u005e\u0060\u007b-\u007e]/g, ""));
console.log($.grep( ${result.data}, function(e){ return e.id == id; }));
console.log(JSON.parse(${result.data}));
All produce same error.
Now I am still trouble in it . Any suggestion would be appreciated. My main point to get is I want to use my object array without any error.Please help me.
What ${result.data} does is basically output datas.toString(). It depends on the structure of the User object what the output will be.
The best thing to do is using a Java Objects to JSON serializer like Gson or Jackson and write a Servlet to output the data as JSON.
Gson
Gson gson = new Gson();
String json = gson.toJson(datas);
See Gson user guide.
Jackson
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(datas);
See Jackson documentation.
Servlet
In your Servlet you can output the generated JSON with the correct content type:
response.setContentType("application/json; charset=UTF-8");
try (OutputStream os = response.getOutputStream())
{
os.write(json.getBytes());
os.flush();
}
This way you can simply load your data using jQuery.getJSON().
Now I am fine with that..
<c:set var="results" value="${result.data}" />
<script type="text/javascript">
var results = jQuery.makeArray("${results}");
alert(results.length);
alert("${results[0].attributeName}");
</script>

Passing (and parsing!) JSON objects through MVC4

I'm confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript.
I'm also not sure if I'm correctly parsing the JSON objects at the right points...
My controller is returning a PartialView with a json object ("Variables" is a list of data e.g. Id=2012, Name=BillyJoel, Value="£2,000"):
public ActionResult JavascriptConstants() {
var variables = Service.Obtain<VariableService>().All().ToList();
var json = new JavaScriptSerializer().Serialize(variables);
return PartialView("JavascriptConstants", json);
}
My View then makes this data available to my scripts by creating this variable:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object?
I've tried changing my JS to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I'm assuming when it hits the "I" of "Id).
Any help much appreciated, thanks.
I found the issue:
The issue was the use of JavaScriptSerializer().Serialize(foo) as this was creating a JSON object that contained newlines and tabs instead of replacing them with \n and \t.
$.parseJSON() cannot handle newlines and so throws up unexpected token error.
This was corrected by importing the JSON.NET package and using :
var json = JsonConvert.SerializeObject(variables);
This passed a JSON object with newlines and tabs replaced with \n's and \t's. Which can then be made accessible to the View using:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
and finally in the script using:
var variableList = $.parseJSON(mvcListOfVariablesInDB)
Hope this helps someone else one day...

How to store a json array with .NET?

I Have a json array like
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]
How can i pass(to the backend) and store(in db) that javascript object with asp.net??
EDIT:
OK to make it clearer, in some page, i got a javascript object
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
, how can i pass it to some handler (like using
`$.post({url:"handler.ashx", data:array})
??), then in backend how can i save it into database or load this array later??
OR:
I'll appreciate it if u teach me how to convert
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
into:
var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]';
EDIT2:
Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
You have several options when dealing with JSON on .NET
You can simply keep the array as is in the DB and retrieve it as is and use it
You can parse it into an Object using JSON.NET Library
for example on the 2nd case you simple use the JSON.NET method:
Newtonsoft.Json.Converters.KeyValuePairConverter
Or be fancy and use a Custom Deserialize as it's really easy to pass to and from JSON.
Let's imagine that you are posting something like this:
$.post("myForm.aspx",
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}],
function() {
// all done.
});
This will be converted to A,B,C when requesting the data using Request.Form["name"] or simply Request["name"] so you should change all the naming convention first and then you can simple use Request["nameA"], Request["nameB"], etc...
You would store it just like any other string you wanted to store in the database. If you want to re-instantiate it later in JavaScript you use the eval() function on the string to convert it back into an object.
The best way to do this is to de-serialize the json into object and save it to db as records.
Check JSON.NET library http://json.codeplex.com/
public class MyObj
{
public string name{get;set;}
public string value{get;set;}
}
void Main()
{
string json ="[{\"name\":\"A\",\"value\":\"A\"},{\"name\":\"B\",\"value\":\"B\"},{\"name\":\"C\",\"value\":\"C\"}]";
IList<MyObj> arr = JsonConvert.DeserializeObject<IList<MyObj>>(json);
foreach(MyObj o in arr)
{
//add each object to db...
Console.WriteLine(o.name+":"+o.value);
}
}
Ok it turns out that using JSON.parse and JSON.stringify is a not-bad solution.

Categories

Resources