How to convert any array to json dynamically - javascript

I am trying to get a file from user, convert it into an array and need to develop a histogram. For developing a histogram, I need to have that data in json format. Though there are enough example to convert an array into json hard coded, but I am not able to find a single example to convert it dynamically on real time basis. Here is my code:
<input type="file" name="F1" id="F1" size="80">
<input type="button" value="Read" name="B1" id="B1" onclick="execFile()">
function execFile() {
// main function to open, parse, and then render
var myfile=document.getElementById("F1")
arr = readCSV(myfile.value);
// parse csv line by line
for (var i=0;i<arr.length;i++) {
arr[i] = parseLineCSV(arr[i]);
}
for (var i=0;i<arr.length;i++) {
document.write(arr[i]);
}
}
So, I need to pass an array arr to convert to json. I found this code from another user but it seems not working for me.
for(var i=1;i<arr.length;i++) {
var tmp_values = [];
alert(arr.length);
for (var l=1;l<arr[0].length;l++) {
alert(arr[0].length);
tmp_values.push({label: arr[0][l], value: arr[i][l]}); //label + value respectively
alert("2");
}
jsonObj.push({key: arr[i][0], values: tmp_values}); //key
alert("3");
}
I am doing some mistake as I am able to get only arr.length and alert 3.. I am doing some mistake with push function, but cant figure out what. So , please help

I found this solution, normally this should do the trick.
var myJsonString = JSON.stringify(yourArray);
see here for more :
Convert array to JSON

Related

Split json data using comma

I have a json which has a key "tag", which is returning data like this
"tags": "jname,gender,city"
but i want to append these value in separate span like below
<div class="info">
<span>jname</span><span>gender</span><span>city</span>
</div>
I am trying with this
$.getJSON("data.json", function(tagsposts) {
var items = [];
splitsVal = tag.split(",");
for (var i = 0; i < splitsVal.length; i++) {
obj.push({name:splitsVal[i]});
obj[i] = '<span>' + obj[i] + '</span>';
$('.tags-div').append(obj[i])
}
$.each(tagsposts, function(key, val) {
items.push('' + val['tags'] + '');
});
$('#tagsposts').append(items.join(""));
});
Am I doing correct
You're trying to split an undefined variable:
function(tagsposts) {
var items = [];
splitsVal = tag.split(","); // but tag doesn't exist...
(If you look at your browser console, which you should get into the habit of doing, you'll get a very clear message about why this isn't working: "ReferenceError: Can't find variable: tag".)
Since you haven't provided your JSON it's not possible to say exactly how to fix this. Assuming the full JSON is of the form
{"tag": "foo,bar,baz"}
then you would want
splitsVal = tagsposts.tag.split(",")
If there's more structure than that inside the JSON, you'll need to crawl down through that parsed object to find the "tag" value(s) you need.
There are lots of other problems here, however.
You also try to push onto an undefined array named obj; you'd need at least a var obj = [] outside that for loop. Though it's not clear why you're using obj at all, or trying to draw an object {name: val} into the DOM instead of just the value. What you're trying to do is just read splitsVal[i] so you can just do this:
for (var i = 0; i < splitsVal.length; i++) {
$('.tags-div').append('<span>'+splitsVal[i]+'</span>')
}
And you try to iterate over tagsposts as if it's an array when generating the #tagsposts contents. (Is your JSON an array? If so you need to iterate over it when getting the tag values too.)

for loop in javascript to access elements incrementally

I am preparing a chart in Javascript.
I have an array element named groupedByWeek
this groupedweek is derived from JSON data. Now i am having it in form of child arrays like this: groupedByWeek = Object { 1: Array[4], 2: Array[7], 3: Array[3] }
screenshot of console is here:
Now i want to parse each of groupedByWeek elements for graph, for the following code:
function increment(){
var i = groupedByWeek[1];
barChart1.parse(i,"json");
for (; i <= groupedByWeek.length; i++){
barChart1.parse(i,"json");
}
}
and
<input type="button" onClick="increment()" value="Next"/>
but this is not working!
Infact nothing is working out inside for loop while i am doing console.log()
If i am doing like this then it's working for 1st elemnt only!!:
var i = groupedByWeek[1];
barChart1.parse(i,"json");
please give me a hint how to work it out!
You have several problems:
Your array is containing an object, not an index.
You spelt length as legnth.
You should be attempting to iterate through your object, rather than an Array. So you would do something along these lines:
Javascript:
for(var index in object) {
// Do something.
}
jQuery:
$.each(object, function(index, value) {
// Do something.
});
I believe that was your original goal, iterate your object not a collection of the items.

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

javascript/jQuery: how do you dynamically turn attribute values into object keys? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert form data to JS object with jQuery
Here is my problem, I have a whole bunch of elements that look like this...
<input type="email" id="email" data-item="email" data-key="contact_details"/>
<input type="tel" id="mobileNo" data-item="mobileNo" data-key="contact_details"/>
<input type="text" id="sleeve_length" data-item="sleeve_length" data-key="measurements"/>
<input type="text" id="inseam" data-item="inseam" data-key="measurements"/>
Each element has a 'data-key' and 'data-item' which corresponds to the json form i'm trying to turn them into, which will look something like this...
{
"measurements" : {"sleeve_length" : value, "inseam" : value},
When each data-item is unique... and like this when it isn't...
"contact_details" : [
{"email" : value, "mobileNo" : value},
{"email" : value, "mobileNo" : value}
]
}
Now because my web app involves many forms, I need a way to dynamically transform the markup above into these json strings... but I can't seem to wrap my head around it!
Does anyone have any idea how I can approach this?
Something like so:
var json = {};
$('#path .to input').each(function(e) {
var key = $(this).attr('data-key');
var param = $(this).attr('data-item');
var obj = {};
obj[param] = $(this).val();
// If we already have a record...
if(key in json) {
// If it's not an array, make it an array
if(typeof(json[key].push) != 'function')
json[key] = [ json[key] ];
// Toss it on the pile
json[key].push(obj);
} else {
// There's only 1 thus far, keep it k/v
json[key] = obj;
}
});
etc. Fairly basic, the key points just being testing whether or not the key you're working with exists or not, and if so, converting it to an array.
Edit: this is untested, but it should work.
Edit 2: revised code so your hash key vars don't come across as strings.
You could let some JS MVC / MVVC library do this for you. For example, Knockout. I haven't used it myself yet, but from a glance it seems neat. You define mapping between your JSON object and HTML form fields, and the library would monitor form fields and update the JSON object (a "view model").
Something like:
var myJson = {};
// jQuery
$('input').each(function () {
myJson[$(this).attr('data-key')][$(this).attr('data-value')] = $(this).val();
});
// Native JS
var els = document.getElementsByTagName('input');
for (var i = 0, l = els.length; i < l; i += 1) {
myJson[els[i]['data-key']][els[i]['data-value']] = els[i].value;
}
Should do the trick. It loops through all of the input elements on the page and puts the data found in each element into an object with the key data-key and sets that equal to an object with the key data-value and the value the value of the input element.
Helpful?
Edit: Is that better? I don't know what I was thinking.

Get value of JSON object with inner objects by HTML form field name without eval

I have a problem like this Convert an HTML form field to a JSON object with inner objects but in to the other direction.
This is the JSON Object response from the server:
{
company : "ACME, INC.",
contact : {
firstname : "Daffy",
lastname : "Duck"
}
}
And this is the HTML form:
<form id="myform">
Company: <input type="text" name="company" />
First Name: <input type="text" name="contact.firstname" />
Last Name: <input type="text" name="contact.lastname" />
</form>
And this is the (pseudo)code:
var aFormFields;
for (var i = 0, iMax = aFormFields.length; i < iMax; i++) {
var sFieldName = aFormFields[i].getAttribute('name');
eval("sFieldValue = oResponse."+sFieldName);
}
Ok my solution works, but i looking for a good way to remove the evil eval from the code.
And the solution should also work for form fields with any count of dots in the field name.
Instead of:
eval("sFieldValue = oResponse."+sFieldName);
Use for single dotted fields:
sFieldValue = oResponse[sFieldName];
This will retrieve the value via its key.
Now if you need more than that you need to do the following:
Split sFieldName on .
Loop over that array and go down in oResponse till you reach the value that you desire
Code could look like this:
var node = oResponse, parts = sFieldName.split('.');
while(parts.length > 0) {
node = node[parts.shift()];
}
// node will now have the desired value
Further information on "Member Operators":
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators
This works for a single property:
sFieldValue = oResponse[sFieldName]
But it won't work for nested data like contact.firstname.
For that, split the name by dots, and use loop through each name:
var aFormFields;
for (var i = 0, iMax = aFormFields.length; i < iMax; i++) {
var aFieldNameParts = aFormFields[i].getAttribute('name').split(".");
var oFieldValue = oResponse;
for(var j=0; j<aFieldNameParts.length; j++) {
oFieldValue = oFieldValue[aFieldNameParts[j]];
}
var sFieldValue = oFieldValue;
}
Note: if a property does not exist, an error will occur. You might want to check whether oFieldValue[ aFieldNameParts[j] ] exists or not.
While it is possible, I wouldn't loop over the input fields, but over the JSON object:
function fillForm (form, data, prefix) {
prefix = prefix ? prefix + "." : "";
for (var x in data) {
if (typeof data[x] === "string") {
var input = form.elements[prefix + x];
if (input)
input.value = data[x];
} else
fillForm(form, data[x], prefix + x);
}
}
fillForm(document.getElementById("myform"), oResponse);
(untested)
Assuming your naming scheme is consistent, you can convert the dot-notation into subscripts. You'd have to split the field name on the period and iterate or recurse over the tokens, converting each into a subscript. Of course this assumes that oResponse always contains a value for every field.
for (var i = 0; i < aFormFields.length; i++) {
var sFieldName = aFormFields[i].getAttribute('name');
var tokens = sFieldName.split('.');
var cur = oResponse;
for (var j = 0; j < tokens.length; j++) {
cur = cur[tokens[j]];
}
sFieldValue = cur;
}
please treat this as a combination of answer and question :)
i am currently trying to get my server to jsonify the data that i get sent from a form just like you...
in my case the form will in the end create a json object with multiple subobjects that can have subobjects which can have... as well.
the depth is up to the user so i should be able to support infinite recursion.
my "solution" so far just feels wrong, but it correctly does the job,
the function getRequestBody gets fed a req.body object from expressjs,
this is basically an object with the following mapping:
{
"ridic-ulously-deep-subobject": "value",
"ridic-ulously-deep-subobject2": "value",
"ridic-ulously-deep2-subobject3": "value",
}
the following html is in use:
<form>
<input name="ridic-ulously-long-class-string" value="my value" />
</form>
and the javascript function (that should work genericly, feed it a req.body object like above and it will return a json object):
function getRequestBody(reqB){
var reqBody = {};
for(var keys in reqB) {
var keyArr = keys.split('-');
switch(keyArr.length){
case 1:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
reqBody[keyArr[0]] = reqB[keys];
break;
case 2:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
if(!reqBody[keyArr[0]][keyArr[1]]) reqBody[keyArr[0]][keyArr[1]] = {};
reqBody[keyArr[0]][keyArr[1]] = reqB[keys];
break;
case 3:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
if(!reqBody[keyArr[0]][keyArr[1]]) reqBody[keyArr[0]][keyArr[1]] = {};
if(!reqBody[keyArr[0]][keyArr[1]][keyArr[2]]) reqBody[keyArr[0]][keyArr[1]][keyArr[2]] = {};
reqBody[keyArr[0]][keyArr[1]][keyArr[2]] = reqB[keys];
break;
case 4:
// ...
//and so on, always one line longer
}
return reqBody;
}
this just feels wrong and its only covering 5 levels of subobjects right now,
it might happen that an application has enough functionality to reach seven or even ten levels though.
this should be a common problem, but my search effort turned up nothing within 10 minutes,
which usually means that i am missing some keywords
or
that there is no viable solution [yet] (which i cant really imagine in this case).
is there someone out there who has imagination and logic sufficient enough to unspaghettify this or will i just have to expand this function with even more clutter to get me down to 10 possible sublevels?
i think that in the end it wont make a big difference performance wise,
but i would really like NOT to create this awful behemoth :D
have fun
jascha

Categories

Resources