How to read an external JSON file as a string in javascript? - 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);

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

Removing instances of a string from a JSON file and then parsing it

I have a JSON file with a lot of content and I load it with the fs Node.js module. But when I look in the JSON file I noticed there is a string of characters attached to many of the field names that make it impossible to target in JS. It looks something like this:
"bk:ParentField": {
"bk:Field": "Value",
"bk:Field2": "Value2"
}
I want to remove the bk: part because I am unable to target the objects with them in it. My code looks like this :
var contents = fs.readFileSync("results.json");
var jsonContent = JSON.parse(JSON.stringify(contents).replace(/bk:/g, '' ));
The problem that whenever I try to target an item after running the code above, I get an error saying an undefined or if I do something like jsonContent['bk:ParentField'] I still get an undefined error.
Any ideas on why this would happen? Or is there a workaround to targeting the objects with the 'bk:'?
The function readFileSync returns a buffer if an encoding is not provided and JSON.stringify takes an Object not a string or buffer.
Just call toString() on the contents buffer before using replace() and then use JSON.parse to create a JavaScript Object:
fs = require('fs');
var contents = fs.readFileSync("test.json");
var data = JSON.parse(contents.toString().replace(/bk:/g, ''));
Or provide an encoding:
fs = require('fs');
var contents = fs.readFileSync("test.json", "utf-8");
var data = JSON.parse(contents.replace(/bk:/g, ''));
Both methods yield the expected result and allow properties to accessed with the . operator:
console.log(data.ParentField.Field);
The replace is not strictly required if you don't mind accessing properties like so:
var data = JSON.parse(fs.readFileSync("test.json", "utf-8"));
console.log(data["bk:ParentField"]["bk:Field"])
It seems that your problem is not the : in the object keys, but the fact that there are no enclosing {} in your JSON string, which makes it invalid. See this example:
var parsed = JSON.parse(`{
"bk:ParentField": {
"bk:Field": "Value",
"bk:Field2": "Value2"
}
}`)
console.log(parsed['bk:ParentField'])

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

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);
}

How to get json value in js code?

I have a json code and i want get json value units_num in alert jQuery. How can don it?
My json code:
[{"id":"11","name":"hiih","units_num":00}]
I tried as in js code: http://jsfiddle.net/Wj8ZL/
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":00}]');
alert(obj['units_num']); // This don't work
var t = JSON.parse('[{"id":"11","name":"hiih","units_num":00}]');
alert(t['units_num']) // This don't work
Your json contains an array of objects, even if there is only one in there. So you need to access that first object in the array
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":"00"}]');
alert(obj[0]['units_num']);
#TravisJ gave a big part of the issue, the other one being quite easy to spot if you read the error log:
"units_num":00
is not valid. It should read
"units_num":0

javascript get nested array elements

in javascript how do I get individual elements out of this array?
http://pastebin.com/n8yrnCpf
I need to loop through it and format the data
how would I get array[0][1][1], for instance
and perhaps there is some json script for doing it quickly
Json comes from J ava S cript O bject N otation. It's a javascript-compatible format, so you can loop through it, and access it as you need. In other words, you do can get array[0][1][1].
If what you're asking for is how can you receive a JSON in a string and convert it to an "usable" JavaScript variable, you can do that this way:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = JSON.parse (json_string)
console.log (parsed_json[0][0])
Or, if you use old browsers (IE7 and so), you can use JQuery and its elder-safe function parseJSON:
var json_string = "[[['whatever','and'],['more','whatever']]]"
var parsed_json = $.parseJSON (json_string)
console.log (parsed_json[0][0])

Categories

Resources