parsing json without knowing the identifiers in javascript - javascript

I have a JSON payload from a REST service that looks something like this:
var jsonify = JSON.stringify(theReturnedData);
console.log(jsonify) =
{
"f-012839": {
"name": "Bob",
"email": "asdf#gmail.com"
}
}
How do I access, for example, the email value without knowing what "f-012839" is?
Here is what I have tried so far without success:
var name = jsonify[0].name;
var name = jsonify.name;
The "f-012839" value is dynamic and I won't know what it is beforehand. It'd be nice if I could get to the "name" and "email" elements without having to know what the "f-012839" key would be. Or, is it possible to take a subset of the returned JSON, so that instead of having the above value, it could be something like this:
{
"name": "Bob",
"email": "asdf#gmail.com"
}
If that's possible, I should be able to get any of those values by simply doing the below, right?
var name = jsonify.name;
Any help would be greatly appreciated. Thanks SO!

for(var key in theReturnedData) {
theReturnedData[key] // This is the object you want access to
}
Update Also make sure to implement a check for each key. You need to filter out the properties that could be inherited from the objects Prototype (lots of frameworks add custom properties to object Prototypes. You can check that through Object.hasOwnProperty(property_name), so basically use this loop:
for(var key in theReturnedData) {
if(!theReturnedData.hasOwnProperty(key)) continue;
theReturnedData[key]
}

for(field in JSON.parse(jsonify)) {
firstObject = jsonify[field];
console.log(firstObject.name);
console.log(firstObject.email);
}

Related

How to pass an array of objects through a query string according to REST?

What is the best practice to pass an array of objects throught query string in REST style?
For example, the array:
examples[] = [
{
name: "foo",
value: "1"
},
{
name: "bar",
value: "2"
}
]
I thought about it:
/items?examples[0][name]=foo&examples[0][value]=1&examples[1}[name]=bar&examples[1][value]=2
Are there other ways to do this?
Upd:
I need readable URL to show it to the user in the address field. It should display state of some filters in the table, I'm not sending it to the backend.
Since you're parsing this manually in JS, you could keep the structure you have and just write a parsing function
var items = {};
location.search.split("?")[1].split("&").map((q) => {
var [token, value] = q.split("="),
[idx, key] = /\[([0-9+])\]\[(\w+)\]/g.exec(token).slice(1, 3);
if (!items[idx]){
items[idx] = {};
}
items[idx][key] = value;
})
This will yield you something with a structure like
{
"0": {
"key1": "data"
"key2": "data:
},
"1": {
"key1": "data"
"key2": "data"
}
}
If you need it to end up an array, it would be pretty easy to convert, but keeping it as an object with numeric strings for keys will prevent an error if it's not sequential.
Also, note there's no error checking or anything here, so if you're going to have query string params that aren't in that format, you'll want to test for that and handle them differently.
You shouldn't take care about how pass data for a backend, Angular do it for you.
About your example, you probably want to update or save several item. So it's not into the url that you will pass your data but into the Request Body :
this.httpService.post(yourUrl, examples, yourHttpOptions).subscribe( (response) => {
// you manage your response data
});
REST does not care how you encode information into your identifiers. You can use any scheme you want, so long as it is consistent with the production rules defined by RFC 3986.
REST cares a little bit about how you share information about creating URI, in the sense that that information should be shared in some readily standardizable form, like an HTML form, or a URI Template.
We don't, to my knowledge, have a "readily standardizable form" that describes how to transform a json array to a query string.
But... REST does allow code on demand; embedding, for example, a bunch of java script into a resource where that javascript knows how to encode the json into the URI... that is in bounds, so long as you have the code on demand itself referenced in a readily standardizable way (like we have with HTML and script tags).
In practice? urlencode the json representation and put it onto the query string directly. That will get you through until you start to discover the real requirements that your URI design needs to support (requirements like: operators needing to be able to understand the access logs).

jquery Updating key of a nested object

I've a json string that I've turned into an object with parseJSON (where #get_my_json_data is a textarea to enter json)
var data = jQuery.parseJSON( $("#get_my_json_data").val() );
cool, I've now got an object to see the whole structure.
What I need to do is to alter the KEY of one node. BUT.. I don't know what it is (so can't just do a stringify and search/replace). I DO know the exact position that it'll be...
Here's a sample structure or the json in the textarea.
{
"MasterData": {
"|-|-|ID|-|-|": {
"menu": {
"Tabs": [
{
"Name": "Home",
"TabText": "Home"
},
.........
I need to find the KEY of the second item, in this example, it's: '|-|-|ID|-|-|'
When they edit again, it'll be different. SO how on earth can I update the node key AFTER MasterData and write the whole thing?
I've tried an $.each loop but it just keeps killing the whole 'array'
---- UPDATE ---
I ended up doing this and it worked great!
var data = jQuery.parseJSON( $("#get_my_json_data").val() );
var keys = Object.keys( data.MasterData );
data.MasterData[$(this).val()] = data.ConteMasterDatatData[keys[0]];
delete data.MasterData[keys[0]];
$("#get_my_json_data").val(JSON.stringify(data));
Soo if i understood what you want, you want to replace the property name in the parsed object.
Try this:
//Get the keys
var innerkeys = Object.keys(myObject.MasterData);
//Create a property with the information from the first key
myObject["myNewKey"] = myObject.MasterData[innerkeys[0]];
//Delete old property
delete myObject.MasterData[innerkeys[0]];
If you parse the object to json it should be as you expected (not tested)
Information obtained from:
how-to-list-the-properties-of-a-javascript-object
how-do-i-remove-a-property-from-a-javascript-object

loop through CouchDB fields in document (validate_doc_update)

I am trying to loop through the fields in a CouchDB document and check that the old version of the field and new version are the same (as part of my validate_doc_update). However, I would like to do the equivalent of a "foreach field in documents, check to make sure they are the same", instead of having to say something like
oldrev.document.field1 == newrev.document.field1, oldrev.document.field2 == newrev.document.field2,
blah blah. Is there a way
to do this with CouchDB fields, or do I have to specify the name of each field? It would be nice to not type them all in, and if we ever change the field names, to not have to come back in and tweak things.
A JS for in loop should suffice:
for (var key in newrev) {
if (newrev.hasOwnProperty(key) {
if (oldrev[key] === newrev[key]) {
// they are the same
}
}
}
There is one thing you'll need to be cautious of here, and that is that deleting/adding fields between revisions may be harder to validate.
I'm pretty sure Object.keys is available to SpiderMonkey, so you may need to use that to compare the number of keys between old and new.
The values passed as newDoc, and oldDoc parameters to validate_doc_update function are Javascript objects: you compare two documents as you compare any JS objects. There no "CouchDB field".
You can write custom code, or you can use a JS library like Underscore.js. You can include it as a CommonJS module. The only problem is the _rev field. My approach is to keep CouchDB metadata separate from document data, by putting the data in a data field. For example:
{ "_id": "ID", "_rev": "REV", "foo": "bar", "baz": [1, 2] }
becomes
{ "_id": "ID", "_rev": "REV", "data": { "foo": "bar", "baz": [1, 2] } }
Then the comparison can be done with
function(newDoc, oldDoc) {
var _ = require("underscore");
if (!_.isEqual(newDoc.data, oldDoc.data)) {
// something changed...
}
}

How to document JavaScript/CoffeeScript data structures

I am looking for a descriptive way to document the used data structures in my JavaScript application. I find it hard to get this done due to the dynamic character of JavaScript.
For instance, what could be a good way to tell, that a used variable distance is a two-dimensional array with length i and j and stores numbers between -1 and MAX_INT. I could think of something like this:
distance[i][j] = -1 <= n <= MAX_INT
What about an object which is used as a map/dictionary for certain data types, what about a two-dimensional array where the first element of an array defines other data then the rest, etc.
Of course, it is always possible to document these things in a text, I just thought, maybe there is a well known and used way to do this in a semiformal way.
Although it's not too widely adopted (yet?), there is a draft standard for JSON schema. I'm just learning it myself but you could write a schema for your two-dimensional array (wrapped inside of an object) as:
{
"description":"Two dimensional array of numbers",
"type":"object",
"properties":{
"two-d-array":{
"description":"columns",
"type":"array",
"items":{
"description":"rows",
"type":"array",
"items": {
"description":"values",
"type":"number",
"minimum":-1,
"maximum":Number.MAX_VALUE
}
}
}
}
}
or simply:
{
"type":"array",
"items":{
"type":"array",
"items": {
"type":"number",
"minimum":-1,
"maximum":Number.MAX_VALUE
}
}
}
There is no CoffeeScript implementation that I know of, but there is a list of several JavaScript validators here. I'm playing with the one that's written by the spec authors called (simply enough) json-schema and I like it well enough calling it from CoffeeScript.
What I tend to do in my JavaScript when I am replicating a lot of data models is to write out what their class definition would be in comments. I am not sure if this is what you meant with your question.
// JavaScript Class jsHomeLocation
// jsHomeLocation{
// string name
// string address
// }
var jsHomeLocation = {};
jsHomeLocation.name = "Travis";
jsHomeLocation.address = "California";
You could also use javascript objects to track the information of the example, a two-dimensional array
var distanceData = {};
distanceData.type = "two-dimensional array";
distanceData.length = i * j;
distanceData.min = -1;
distanceData.max = MAX_INT;

create json string on client side

I am trying to create the JSON string / object that is equivalent to the following data on the server side. can somebody help?
Public Shared Function GetData() As List(Of Employee)
Dim list As New List(Of Employee)()
Dim newEmployee As New Employee()
newEmployee.EmployeeID = "1"
newEmployee.FirstName = "Sridhar"
newEmployee.Title = "Programmer"
newEmployee.BirthDate = "8/10/1979"
newEmployee.TitleOfCourtesy = "Programmer"
list.Add(newEmployee)
Return list
End Function
Employee is a class with the properties EmployeeId, FirstName, Title, Birthdate, TitleOfCourtesy.
Thanks,
sridhar.
Keep in mind that in Javascript there is no concept of a class, only objects. This also carries over into JSON. Look at this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
If you look at the first line, the "Employee" symbol does absolutely nothing for the JSON. Remember that we're dealing with ONLY objects.
Thats why this works, like you said.
[
{"EmployeeID":1,
"LastName":"Duggireddy",
"FirstName":"Sridhar",
"Title":"Programmer",
"TitleOfCourtesy":"Programmer",
"BirthDate":new Date(303091200000)}
]
To make this programatically, declare your employee objects, and just add them into an array, like so:
var employees = [];
employees.push(employee1); // you would use a loop, of course
employees.push(employee2);
...
var jsonString = parser.toJSON(employees); // or whatever you use.
That should give you a list of objects. Always ignore the class in JSON... .NET during the deserialization will attempt to coerce the object into that particular class. You only have problems if this fails - maybe because a variable is missing or of the wrong type.
Why not just use JSON.NET and let it handle encoding/decoding for you?
It will look like
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
}
}
Reference
I believe multiple instances of Employee in the JSON would look like this:
{"Employee" :
{
"EmployeeID":"1",
"FirstName":"Sridhar",
etc...
},
{
"EmployeeID":"2",
"FirstName":"Joe",
etc...
}
}
Maybe that is what you need?
There's a good jQuery plugin for JSON. It lets you go from a JavaScript object to JSON very easily.
http://code.google.com/p/jquery-json/

Categories