How to access a json object in javascript files from a model passed to the view - javascript

I have a JSON object in my database that contains html inside it. I pass the object as part of a model to my view. I need to access the object and read it in the javascript files for the page. However when i try and assign the object to a global variable in my html file i cannot access it in my javascript file.
I tried reading the object as a string it returns decoded html (
"page-1":) which i cant do anything with. If i call #Html.Raw(#Model.CourseContent.ExpectedResult) it created the JSON object as expected. However in my javascript file it is listed as undefined. I have no idea how to solve this.
#model DataTransferObjects.Models.UserCourseAndContent
<script>
var totalPages = '#Model.CourseContent.TotalPages';
var expectedResults = #HTML.Raw(#Model.CourseContent.ExpectedResult)
</script>
The json object that comes out when i use the above code looks like
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
I expected it to be an actual json string but instead ive got an object (?) i am confused as to how to decode the html out of it then turn the resulting json obejct into a json string to be read in the javascript file.
Any help would be great!

var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));
// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];

Related

How to append an item to a JSON stored in a file?

Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Here is the code:
Thanks.
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
Read file content.
Parse JSON text into an object.
Update the object in memory.
Write object in JSON format back to the file system.
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

load JSON with JQuery

Is it possible to load JSON file once, and in further call will use loaded JSON (for ex. from cache)?
The easiest way to achieve this is to use the localStorage of JavaScript.
Let's assume you have an object named object.
You can store it this way:
// parse Object to JSON, then store it.
let jsonObject = JSON.stringify(object);
localStorage.setItem('myObject', jsonObject);
And if you want to use it again, do it this way:
// load it from storage and parse the JSON to Object.
let jsonObject = localStorage.getItem('myObject');
let object = null;
if(jsonObject){
object = JSON.parse(jsonObject);
}
Then change it according to your needs and store it again.
You can delete it by
localStorage.removeItem('myObject');
There are so many ways,
You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778
You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778
For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html
For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/

How to get Model object metadata properties in Javascript AutoDesk

I am working with AutoDesk Forge Viewer (2D) in Javascript with Offline svf file.
I have converted the .dwg file to svf file.
How can I get Model Object Metadata properties in Javascript like we get using the api "https://developer.api.autodesk.com/modelderivative/v2/designdata/{urn}/metadata/{guid}/properties" ?
I tried using viewer.model.getProperties(dbId,function,funtion), but this only gives me details of particular to that dbId but i want the list of properties.
Please help me with this.
firstly, the other blog talks about how Model Derivative extracts properties. In theory, if you get 'aka json (json.gz)' or 'sqlLite (sdb/db)', you would be able to extract yourself by other tools.
How properties.db is used in Forge Viewer?.
I believe you have known http://extract.autodesk.io/ as you said you have downloaded SVF. http://extract.autodesk.io/ provides you with the logic to download translated data, including json.gz and sqlLite db.
While if you prefer to dump all properties within browser by Forge Viewer, the only way I can think is as below:
function getAllDbIds(viewer) {
var instanceTree = viewer.model.getData().instanceTree;
var allDbIdsStr = Object.keys(instanceTree.nodeAccess.dbIdToIndex);
return allDbIdsStr.map(function(id) { return parseInt(id)});
}
var AllDbIds = getAllDbIds(myViewer);
myViewer.model.getBulkProperties(AllDbIds, null,
function(elements){
console.log(elements);//this includes all properties of a node.
})
Actually, I combined two blogs:
https://forge.autodesk.com/cloud_and_mobile/2016/10/get-all-database-ids-in-the-model.html
https://forge.autodesk.com/blog/getbulkproperties-method

Creating a json obj from a string when working without a net connection?

I have a json object returned from a third party api, it looks like:
{"version":"1.0","encoding":"UTF-8"}
I'm going to be working on my project without a network connection, so I have to do everything locally. How can I create an instance of a json object locally for testing? Say I copy the above string, can I do something like:
var json = null;
if (debugging_locally) {
json = new jsonObj('{"version":"1.0","encoding":"UTF-8"}');
}
else {
json = doAjaxCall();
}
doStuffWithJsonObj(json);
so I just want to create a json object from a stored string if debugging locally - how can I do that?
Thanks
Simple as this:
if (debugging_locally) {
json = {"version":"1.0","encoding":"UTF-8"};
}
JSON is valid Javascript syntax.
Therefore, you can paste the JSON directly into the Javascript (not as a string) and assign it to a variable.
Take a look at Resig's post as well. He covers some new JSON parsing capabilities that are currently in the JS engines of Safari, WebKit, Chrome, Firefox.
This way you can test a JSON string that you will be expecting from a web-service, your API etc.
eg.
instead of:
json = new jsonObj('{"version":"1.0","encoding":"UTF-8"}');
you could do:
json = JSON.parse('{"version":"1.0","encoding":"UTF-8"}');

Categories

Resources