Converting an array into JSON - javascript

I need to bring in a csv doc and convert it to JSON, so far I have been able to convert it to an array and from the array I'm trying to build a JSON object.
Below is the JavaScript that builds the JSON, but its not in the structure I need, underneath is an example of the structure required.
var jsonObj = []; //declare object
for (var i=1;i<csvAsArray.length;i++) {
jsonObj.push({key: csvAsArray[i][0]}); //key
for (var l=1;l<csvAsArray[0].length;l++) {
jsonObj.push({label: csvAsArray[0][l], values: csvAsArray[i][l]}); //label + value respectively
}
}
Final output required:
{
"key": "Sample 01",
"values": [
{
"label" : "Something" ,
"value" : 1
} ,
{
"label" : "Something" ,
"value" : 2
}
]
},
{
"key": "Sample 02",
"values": [
{
"label" : "Something" ,
"value" : 5
} ,
{
"label" : "Something" ,
"value" : 4
}
]
}

Simply use JSON.stringify() to convert your array to json string
var jsonString = JSON.stringify(yourArray);

You need to declare the values and push that onto a tmp variable before pushing that index onto the final/main object
var tmp_values, jsonObj = []; //declare object
for (var i=1;i<csvAsArray.length;i++) {
var tmp_values = [];
for (var l=1;l<csvAsArray[0].length;l++) {
tmp_values.push({label: csvAsArray[0][l], value: csvAsArray[i][l]}); //label + value respectively
}
jsonObj.push({key: csvAsArray[i][0], values: tmp_values}); //key
}

This script is a common way to convert an array to JSON in JavaScript.

I'm not a fan of answers like this, but this service in my opinion is good enough to warrant it. It can convert between various data formats including CSV, JSON, XML, HTML table, etc. It even offers variations in output structure for some of the formats.
http://shancarter.github.io/mr-data-converter/

use this code and very simple develop for more two array
function getJSON(arrayID,arrayText) {
var JSON = "[";
//should arrayID length equal arrayText lenght and both against null
if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
and 3 array
function getJSON(arrayID, arrayText, arrayNumber) {
var JSON = "[";
if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "',";
JSON += "number:'" + arrayNumber[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}

Related

Add items to JSON object

I'm picking up a JSON object using a promise:
var x = get();
x.done(function(data) {
for(var i in data) {
}
});
which is returning this data when i do console.log(data);
[{…}]
0:
customer: "9028"
data:
active: "1"
customer: "9028"
description: ""
id: "13717"
inherited: "0"
name: "Out of Hours"
priority: "1"
shared: "0"
sound: ""
__proto__: Object
voip_seq: "4"
__proto__: Object
length: 1
__proto__: Array(0)
so that is working fine, but within my for loop, I want to add 2 items to data
I tried adding this into my .done
var obj = { name: "Light" };
data.push(obj);
But that didn't add to data
My for loop looks like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
If you want to add two more items to your select, you simply need to push new objects into your data array before your loop starts. The objects must contain the structure and properties ("name" and "id" within a "data" sub-property) matching the JSON coming from the Promise, so that your loop code can process them.
In the simplest case, it could be as straightforward as
x.done(function(data) {
data.push({ "data": { "name": "light", "id": 1234 } });
data.push({ "data": { "name": "dark", "id": 5678 } });
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if (data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
});
Demo: https://jsfiddle.net/a286b7fw/1/
In this case I think data is not an array so it hasn't .push() method. You can add property to object like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
// here it will add obj to data
var obj = {name: "Light"};
data = {
...data,
obj
}
}

How to access all nested associative array elements?

Situation : I receive JSON array from jQuery <-> PHP Ajax request. Here's structure of unparsed JSON aray :
{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
And after using JSON.parse(json); the structure looks like :
Focus: Object
brand: "Ford"
id: 2
name: "Focus"
Problem : I want to access all array's '1st tier' elements and use them like an object, but none of the following ways works :
for (var entity in dataTable)
{
formattedText += entity['brand'] + " " + entity['name'] + "<br>";
OR
formattedText += entity.brand + " " + entity.name + "<br>";
OR
formattedText += dataTable[0]['brand'] + " " + dataTable[0]['name'] + "<br>";
}
Any solutions how to read values of all object in this array?
The for..in loop uses keys and does not return the elements themself: for (var key in dataTable)You would then access each element with dataTable[key]. The key is actually the name of the Element.
You where using it as you would use a for..of loop, but that is a new feature not supported in all Browsers yet.
Demo:
var dataTable = {"Focus":{"id":2,"brand":"Ford","name":"Focus"}}
var formattedText = ""
for (var key in dataTable)
{
formattedText += dataTable[key]['brand'] + " " + dataTable[key]['name'] + "<br>";
}
document.write(formattedText)
Object.keys will return array of all the keys of the object
You can loop(forEach/for-loop) through the keys to get the expected output.
Using forEach:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
keys.forEach(function(item) {
str += dataTable[item].brand + " " + dataTable[item].name;
});
alert(str);
Using for-loop:
var dataTable = {
"Focus": {
"id": 2,
"brand": "Ford",
"name": "Focus"
}
}
var keys = Object.keys(dataTable);
var str = '';
for (var i = 0, len = keys.length; i < len; i++) {
str += dataTable[keys[i]].brand + " " + dataTable[keys[i]].name;
}
alert(str);
The correct syntax to write this would be:
When you loop, you'll get the key name in the variable entity and then use that to get the value, also, you need to access the associative array inside the first key i.e. Focus
var dataTable = JSON.parse('{"Focus":{"id":2,"brand":"Ford","name":"Focus"}}');
var formattedText = '';
for (var entity in dataTable.Focus) {
formattedText += dataTable.Focus['brand'] + " " + dataTable.Focus['name'] + "<br>";
}
Sounds like you're using each function in a wrong way. in your each function change arguments to key and value like this:
$.each(dataTable, function (key, value) {
//access key and values here
});
In your case u should iterate again over key and values of your key values.

javascript loop through json response

I want to loop through my json response. My json response looks like this
{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}
What I want is a foreach loop through all lines so i get the keys and the values for every line.
You could iterate like this: (added code-comments for explanation)
var result = document.getElementById("result");
var json = '{"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"}';
var obj = JSON.parse(json);
// json object contains two properties: "line" and "total".
// iterate "line" property (which is an array but that can be iterated)
for (var key in obj.line) {
// key here is the index of line array
result.innerHTML += "<br/>" + key + ": ";
// each element of line array is an object
// so we can iterate over its properties
for (var prop in obj.line[key]) {
// prop here is the property
// obj.line[key][prop] is the value at this index and for this prop
result.innerHTML += "<br/>" + prop + " = " + obj.line[key][prop];
}
}
// "total" is a property on the root object
result.innerHTML += "<br/><br/>Total = " + obj.total;
<p id="result"> </p>
Demo Fiddle: http://jsfiddle.net/abhitalks/ajgrLj0h/2/
.
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
for(var i = 0; i < json.line.length; i++)
{
console.log("Type: " + json.line[i].type + " Name: " + json.line[i].name + " Account: " + json.line[i].account + " Description: " + json.line[i].description + " Balance: " + json.line[i].balance + " Image: " + json.line[i].image);
}
You can do something like that...
var json = {"line":[{"type":"bank","name":"ABN","account":"NL47ABNA0442660960","description":"Bijgewerkt t\/m 30-10-2014","balance":"6.266,55","image":""},{"type":"bank","name":"Rabo","account":"NL89RABO0177896647","description":"","balance":"0,00","image":""}],"total":"6.266,55"};
if(json.line !== undefined && json.line.length > 0){
var key,value;
json.line.map(function(lineObject){
for (key in lineObject) {
value = (lineObject[key] == '')?'unknown': lineObject[key];
console.log(key+":"+ value);
}
console.log("---------------------");
});
}
http://jsfiddle.net/ddw7nx91/
var obj = {"line":[]} //your json here
for(var i=0; i<obj.line.length; i++) {
console.log(obj.line[i].type)
}
obj.line is an array, so you can get his length an cycle it.
This would create an array of lines each with a keys object and a values object.
var response = JSON.parse( {'your':'JSON'} );
var lines = [];
$.each( response, function( line ) {//loop through lines in response
var keys = [];
var values = [];
$.each( line, function( obj ) {
keys.push( Object.keys(obj) );//get keys
for( var key in obj ) {
values.push(obj[key]);//get values
}
});
lines.push({ {'keys':keys},{'values':values} });
});

How can iterate over JSON object and print its properties and their values?

I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`

How to get json data properly in javascript

I'm trying to get the data inside of "attributes" in these json format, but I always get undefined
{ "data": [
{ "attributes":
{
"id":"4977",
"book_id":"651284829",
"provider_id":"1",
"title":"\u96e8\u8272\u30b3\u30b3\u30a2",
"author":"IAM, K.K.",
"price":"170.00",
"rating":"4"
},
...
}
}
This is my code which always returns undefined:
for ( var obj in json.data) {
var att = obj.attributes;
html += "<p>" + att.author + "</p>";
}
You're iterating over the keys of the properties of json.data, not the values of those properties.
Change
var att = obj.attributes;
to
var att = json.data[obj].attributes;
To make it clearer, a different name could be used :
for (var key in json.data) {
var obj = json.data[key];
var att = obj.attributes;
html += "<p>" + att.author + "</p>";
}

Categories