validating JSON file in JavaScript - javascript

My Google Chrome extension uses JSON.parse(oldJSONstring) to create an object with configuration information. The "oldJSONstring" was saved from previous sessions on Chrome's localStorage.
As I sometimes add new features, after I create the new object, I manually validate that all configuration entries exist, if not, I'll set them with default values. This is done, in case it's he firs time a user loads the extension after it updated.
I was trying to think of a more automatic way of doing this, like using a JSON Schmea, but I really don't know where to start, and my first round of google searches didn't produce anything I could use.
Another approach I thought was to iterate on all my Default settings -also stored on a JSON object- and then confirming they exist on the new object... but I just realized I don't know how to iterate a JSON object for all its attributes :)
The end goal of this is that I'd like to forget about validating for new attributes, every time I create a new feature and I publish a new version... does it make any sense? does it make me lazy? :D
Thanks!

Keep the default object handy and use jQuery $.extend to merge the 2 objects.
var defaults={ color:'blue', size:'Large'}
var chromeObj= /* code to grab from storage*/
/* update chromeObj with all key/value pairs in defaults */
/* regardless if they already exist or not*/
$.extend( chromeObj, defaults}
/* code to put chromeObj back to storage*/
Refrence: http://api.jquery.com/jQuery.extend/

There is no such thing as a "JSON object,"* but it's quite easy to loop over a Javascript object's properties: How do I loop through or enumerate a JavaScript object?
* JSON is just a string format, and it's a subset of Javascript object notation

Related

JSON in localforage, efficient way to update property values (Binarysearch, etc.)?

I would like to come straight to the point and show you my sample data, which is around the average of 180.000 lines from a .csv file, so a lot of lines. I am reading in the .csv with papaparse. Then I am saving the data as array of objects, which looks like this:
I just used this picture as you can also see all the properties my objects have or should have. The data is from Media Transperency Data, which is open source and shows the payments between institiutions.
The array of objects is saved by using the localforage technology, which is basically an IndexedDB or WebSQL with localstorage like API. So I save the data never on a sever! Only in the client!
The Question:
So my question is now, the user can add the sourceHash and/or targetHash attributes in a client interface. So for example assume the user loaded the "Energie Steiermark Kunden GmbH" object and now adds the sourceHash -- "company" to it. So basically a tag. This is already reflected in the client and shown, however I need to get this also in the localforage and therefore rewrite the initial array of objects. So I would need to search for every object in my huge 180.000 lines array that has the name "Energie Steiermark Kunden GmbH", as there can be multiple and set the property sourceHash to "company". Then save it again in the localforage.
The first question would be how to do this most efficient? I can get the data out of localforage by using the following method and set it respectively.
Get:
localforage.getItem('data').then((value) => {
...
});
Set:
localforage.setItem('data', dataObject);
However, the question is how do I do this most efficiently? I mean if the sourceNode only starts with "E" for example we don't need to search all sourceNode's. The same goes of course for the targetNode.
Thank you in advance!
UPDATE:
Thanks for the answeres already! And how would you do it the most efficient way in Javascript? I mean is it possible to do it in few lines. If we assume I have for example the current sourceHash "company" and want to assign it to every node starting with "Energie Steiermark Kunden GmbH" that appear across all timeNode's. It could be 20151, 20152, 20153, 20154 and so on...
Localforage is only a localStorage/sessionStorage-like wrapper over the actual storage engine, and so it only offers you the key-value capabilities of localStorage. In short, there's no more efficient way to do this for arbitrary queries.
This sounds more like a case for IndexedDB, as you can define search indexes over the data, for instance for sourceNodes, and do more efficient queries that way.

How to convert javascript array to scala List object

I have inherited some code that uses the Play! framework which has scala.html files that have javascript in them. Play! and scala are all new to me.
One of the javascript functions does a post and gets back a JSON object. It then loops through the JSON object and creates an array.
var myArray = [];
function createArray(){
$.post('/createArray', $('#arrayForm').serialize()).done(function( data ) {
var obj1 = JSON.parse(data);
$.each(obj1, function(idx, obj) {
myArray.push(obj.name);
});
});
return true;
}
It then uses this array (of strings) to create a text input field that does autocomplete using the data in the array.
I want/need to convert this text input to a select dropdown using the Play! #select but the options arg for #select wants a List object (or Map or Seq - just figured List would be easier since I already have an array of strings).
If I manually create the List object, it works fine.
#select(pForm("equipName"), options(scala.collection.immutable.List("Yes","No")))
The problem is I cannot figure out how to convert the myArray array to a List object which I can then pass to the #select options.
I have found a lot of posts that talk about converting a scala List to an array but can't find a way to go the other way. I am hoping it is an easy thing that I can't seem to figure out.
Thanks in advance for the help.
You can not do that. And more precisely - you do not want to do that.
So basically your play application run on server. In your Play application all those .scala html files are compiled to generate some functions.
Now, when a play application receives a request from a client browser, it gets mapped to some controller by by router. The controller does some processing and finally take one of these above functions ( lets say for index.scala.html we get views.html.index ) and call this function with some parameters.
These functions returns some text which is then sent to the client's browser as HTTP response with response header Content-Type:text/html; charset=utf-8 which tells the browser to treat this text as html.
Now, the browser renders the html which has embedded JavaScript and hence runs the JavaScript. So... basically your JavaScrpt code does not exist on server... for play all of it is just text.
Both of these Scala code and JavaScript code are executed at very different times, at different computers and in different environments hence you can not do whatever you are saying.

How to transfer object properties to existing object JavaScript?

Please forgive me in advance as I'm sure this is a noob question (I honestly searched google for an hour before I cam here);
Long Story:
Okay, so I'm creating an application that lists vehicles stored in a database. I have a JavaScript class called Car that is instantiated for each car listing. The class contains default values for everything (make, model, year, color, price, etc) and has a function to use a jQuery ajax request to have my php return the actual values for the car. I pass it with JSON and have a consistent naming convention, so my xhr object in my success function is basically a copy of the car object, only with the correct values. I'm trying to find a simple way to give the xhr object's properties to the car object without manually specifying all 30 options (I know it's doable, but I'm sure there must be a better method, and i'm always up to learn)
Short Story:
How can I use object-x's properties to overwrite object-y's when they have the exact same list of defined properties and both already exist?
Thank you very much in advance!
Well you would simply
$.extend( car, json );
Where car object is the target and json is the object where the correct values are
Docs http://api.jquery.com/jQuery.extend/
Jsfiddle demo http://jsfiddle.net/qApyZ/

JSON parsing a Titanium.App.Properties string

In an app, made with TideSDK; i assign a global variable (shocking I know) to a the JSON parse of a string stored in Titanium.App.Properties:
var workbookArray = JSON.parse(Titanium.App.Properties.getString('workbookArray'));
workbookArray is an array of objects.
And then on the unloading of a page, I assign Titanium.App.Properties string the value of workbookArray, which may have been changed by whoever has used the app:
Titanium.App.Properties.setString('workbookArray', JSON.stringify(workbookArray));
Each time I open the app, however, I'm told that JSON was unable to parse the first code snippet (initializing workbookArray).
Aside from this issue, I don't expect to use the app Properties API for my storage needs in the longterm, I wish i could use indexedDB with titanium. SQL is an option, but is a little messy when it comes to objects. Any other suggestions for a database solution?
Try getList and setList
http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.App.Properties
What is stored in the list?

append object to innerHTML and get that object from innerHTML

here is an example in jsfiddle.
I want to know if I can append a javascript object to innerHTML, that get that object again from innerHTML as object.
something like,
alert((this.innerHTML).html);
that's just an example, don't ask me why do you need this?
I'm trying to edit an existing code, and I have to do this so.
I have to transfer an object via div.innerHTML.
Check this jsfiddle. In it, I add the object to the div as a 'data-'-attribute, using JSON to convert it to a string. After that, adding some comment to the div triggers the DOMSubtreeModified-handler, in which the 'html'-part of the object is retrieved and alerted. It that something to work with?
In this case, quite possible your only option is to convert your object to string and then put that into the element. (This is done by looping through the key, values building the string as you go.)
You would reverse the process to convert it back into an obj.
I know some javascript libary's have helper functions to make this process very simple.
You could try adding the data directly onto the dom element, rather than as its content..
tempDiv.objData = myObject;
It was suggested to use JSON, but no code. So:
function addObjAsJSON(el, obj) {
el.setAttribute('data-myJSON', encodeURIComponent(JSON.stringify(obj)));
}
function getObjAsJSON(el) {
return JSON.parse(decodeURIComponent(el.getAttribute('data-myJSON')));
}
That should allow you to add anything as a serialised object, then get it back. You should add some error checking to make it robust though (e.g. check that you get a string back from the call to getAttribute).
For user agents that don't have built-in JSON support, see json.org which has a link in the javascript section to json.js.

Categories

Resources