How to create JAVASCRIPT ARRAY from external file JSON - javascript

What is the best way to create javascript array from json file?
I have four empty JavaScript array that I would like to populate with data imported from a json file.
var firstname = new Array();
var address= new Array();
var city = new Array();
File Json : "file.json"
[
{"name ": "John", "address": "350 Fifth Avenue", "city ": "New York"},
{"name ": "Mark", "address": "1101 Arch St", "city ": "Philadelphia"},
{"name ": "Jack", "address": "60th Street", "city ": "Chicago"}
]
I try:
$.getJSON('file.json',function (data) {
for (var i = 0; i < data.length; i++) {
firstname.push.apply( firstname, data[i].firstname );
address.push.apply( address, data[i].address );
city.push.apply( city, data[i].city );
}
});
but arrays are still empty.
Thanks in advance
================================ SOLVED ===============================
$.ajax({
async: false,
url: 'file.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
firstname.push( data[i].firstname );
address.push( data[i].address );
city.push( data[i].city );
}
}
})
// Get arrays outside callback function
console.log('result: '+firstname.length); // result: 3

You seem to have the order wrong, data is the array so it's not
data.name[i]
but
data[i].name
and removing the strange apply it would be
$.getJSON('json.js',function (data) {
for (var i = 0; i < data.length; i++) {
name.push( data[i].name );
address.push( data[i].address );
city.push( data[i].city );
}
});
Also note that name is a bad choice for a variable name in the global context.

You have two or three problems.
Your JSON is invalid.
Remove the quotes from around the outside of it.
Seriously consider giving is a .json file extension, then you are more likely to get the right MIME type for JSON. (JSON data files are not JavaScript programs).
File Json : "data.json"
[
{"name ": "John", "address": "350 Fifth Avenue", "city ": "New York"},
{"name ": "Mark", "address": "1101 Arch St", "city ": "Philadelphia"},
{"name ": "Jack", "address": "60th Street", "city ": "Chicago"}
]
You are accessing your data in the wrong order
This is overly complicated and is accessing properties in the wrong order.
name.push.apply(name, data.name[i]);
Forget about using apply. You don't need it.
Then note that your JSON array contains the objects, not the other way around. You need to access the array index before the property name:
name.push(data[i].name);
Remember the A in Ajax
Finally - your code doesn't show how you are testing the result. Remember that Ajax is asynchronous, so that if you examine the values of your arrays outside the callback function, they might not have been populated yet.

Related

create json array and append objects in it from form

At this moment I'm trying to create a json like this.
[
{"name": "set registry key right",
"win_acl": {
"path": "HKCU:\\Bovine\\Key",
"user": "BUILTIN\\Users",
"rights": "EnumerateSubKeys",
"type": "allow",
"state": "present",
"inherit": "ContainerInherit, ObjectInherit",
"propagation": "None"
}
},
{
"name": "Remove FullControl AccessRule for IIS_IUSRS",
"win_acl": {
"path": "C:\\inetpub\\wwwroot\\MySite",
"user": "IIS_IUSRS",
"rights": "FullControl",
"type": "allow",
"state": "absent",
"inherit": "ContainerInherit, ObjectInherit",
"propagation": "None"
}
}
]
I want to create it dynamically trough javascript.
This is what I have now:
function GenerateYaml(btn) {
$('#generatedYamlTextField').removeAttr("hidden");
var id = btn.replace("generateBtn", "");
var moduleName = $("#formpanel" + id).attr("data-title-caption");
//Looping trough panels
$("#formpanel" + id).each(function () {
var json = "[\n{\n\"name\":\"" + "module beschrijving" + "\",\n";
json += "\"" + moduleName + "\": {\n";
//Looping through labels in the panel to create the object
$('label').each(function (index, value) {
var is_last_item = (index == ($('label').length - 1));
if (!is_last_item) {
json += "\"" + value.innerText + "\":"+"\"textboxvalue\",\n";
} else {
json += "\"" + value.innerText + "\":"+"\"textboxvalue\"\n";
}
});
json += "}\n},]\n";
$("#yamltextfield").append(json);
});
}
This is what I get from above code in my textarea:
[
{
"name":"module beschrijving",
"win_acl_inheritance_module": {
"path":"textboxvalue",
"reorganize":"textboxvalue",
"state":"textboxvalue"
}
},]
My problem is that I have multiple panels and I want to add them in the same array so that I get it like the json I showed in the first place.
I hope you guys could help me out. Thanks in advance.
Greetings,
Mouaad
Don't form the json string manually. Just compose your objects, put them in an array, say arr and you can get the json string by:
JSON.stringify(arr);

How to separate a JSON.stringify result

Related Retrieve two lists, sort and compare values, then display all the results
The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.
The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.
Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...
Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.
The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.
I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.
Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(type);
Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.
var data = {
d:{
results: [
{ "Title": "apple", "Type": "rome", "State": null },
{ "Title": "grape", "Type": "fruit", "State": null }
]
}
};
var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Looping Simple JSON Array

For some reason my loop is treating this array as a string and looping through each character.
Here's the structure:
var json = [
{
"featured": "1",
"href": "someurl/",
"property": "some property",
"location": "<strong>Winston-Salem</strong>North Carolina, United States",
"date": "23 Oct",
"year": "2014"
},
{
"featured": "1",
"href": "someurl/",
"property": "Sheraton Albuquerque Airport Hotel",
"location": "<strong>Albuquerque</strong>New Mexico, United States",
"date": "23 Oct",
"year": "2014"
}
]
I'm looping it with:
for(var i = 0; i <= json.length; i++) {
console.log(json[i]);
}
Here's a snippet of the type of output I get:
f
e
a
t
u
r
e
d
"
:
"
1
"
Json is actually a string while you havent serialized it. So it is a string representation of arrays lists and other objects.
If it is an ajax response maybe you have a wrong mime type. So it thinks it is getting a raw string rather than json.
If you are asking such a question I think you probably should read this first JSON
Edit:
If you want to get correct answer you should clarify your question. For example what are you using to get json.
If it is jQuery than you shuld use something like this:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
took it from here
or if you are using pure js you should manually serialize json like this:
var obj = JSON.parse(text);
took it from here
where text variable contains string got from the server or wherever you get it from.

Javascript how to parse JSON array

I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one :
{
"success": true,
"counters": [
{
"counter_name": "dsd",
"counter_type": "sds",
"counter_unit": "sds"
},
{
"counter_name": "gdg",
"counter_type": "dfd",
"counter_unit": "ds"
},
{
"counter_name": "sdsData",
"counter_type": "sds",
"counter_unit": " dd "
},
{
"counter_name": "Stoc final",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "Consum GPL",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "sdg",
"counter_type": "dfg",
"counter_unit": "gfgd"
},
{
"counter_name": "dfgd",
"counter_type": "fgf",
"counter_unit": "liggtggggri "
},
{
"counter_name": "fgd",
"counter_type": "dfg",
"counter_unit": "kwfgf "
},
{
"counter_name": "dfg",
"counter_type": "dfg",
"counter_unit": "dg"
},
{
"counter_name": "gd",
"counter_type": "dfg",
"counter_unit": "dfg"
}
]
}
My problem is that I can't parse this JSON object so that i can use each of the counter objects.
I'm trying to acomplish that like this :
var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
console.log(counter.counter_name);
}
What am i doing wrong ?
Thank you!
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
Here is a working example
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to #Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) {
console.log(jsonData.counters[counter].counter_name);
}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
This is my answer:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt =
'{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.firstName);
}
</script>
</body>
</html>
Just as a heads up...
var data = JSON.parse(responseBody);
has been deprecated.
Postman Learning Center now suggests
var jsonData = pm.response.json();
Something more to the point for me..
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
document.write(contact.phone[1]);
// Output:
// Aaberg, Jesper
// 555-0100
Reference:
https://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript
"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied by a Ext.data.proxy.Proxy (in this case Ext.data.proxy.Ajax) furnished with a Ext.data.reader.Json (for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writers of several kinds.
Here's an example of a setup like that:
var store = Ext.create('Ext.data.Store', {
fields: [
'counter_name',
'counter_type',
'counter_unit'
],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
idProperty: 'counter_name',
rootProperty: 'counters'
}
}
});
data1.json in this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name' is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters' specifies which property contains array of data items.
With a store setup this way you can re-read data from the server by calling store.load(). You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.
This works like charm!
So I edited the code as per my requirement. And here are the changes:
It will save the id number from the response into the environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++)
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}
The answer with the higher vote has a mistake. when I used it I find out it in line 3 :
var counter = jsonData.counters[i];
I changed it to :
var counter = jsonData[i].counters;
and it worked for me.
There is a difference to the other answers in line 3:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData[i].counters;
console.log(counter.counter_name);
}
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
Not sure if my data matched exactly but I had an array of arrays of JSON objects, that got exported from jQuery FormBuilder when using pages.
Hopefully my answer can help anyone who stumbles onto this question looking for an answer to a problem similar to what I had.
The data looked somewhat like this:
var allData =
[
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
],
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
]
]
What I did to parse this was to simply do the following:
JSON.parse("["+allData.toString()+"]")

Accessing data in a multidimensional JSON array with jQuery

I am trying to work out how to access data in an essentially multidimensional JSON array.
My jQuery AJAX request looks like this:
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/ajax/login',
data: 'email='+$("#email").val()+'&password='+$("#password").val(),
success: function(data){
// FIRE ALERT HERE
alert(data.firstname);
},
dataType: 'json'
});
});
This is what i am getting back. User account details, plus a list of products they have against their account.
{
"logged_in":true,
"firstname":"Joe",
"surname":"Bloggs",
"Full_name":"Joe Bloggs",
"email":"email#website.com",
"phone":"+123456789",
"website":"",
"age":"26-35",
"street":"1 Street Ave",
"city":"Townland",
"state":"NA",
"postcode":"1234",
"country":"Australia",
"products":2,
"0":{
"product_no":"1087",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
},
"1":{
"product_no":"24",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
}
}
As you can see, i am alerting the first name, which is fine. I can access everything in the first dimension by using data.key but i'm not sure how then i need to index the next dimension. Obviously I would like to display each of the products somehow.
Suggestions would be most welcome.
Inside your success function you can treat the JSON data as a JavaScript object. You can access the product array and objects inside it like this:
console.log(data.products + " product(s) in data"); // data.products is 2 (integer)
for(var i = 0; i < data.products; i++) { //
var product = data[i.toString()]; // 0.toString() is "0"
// data["0"] is what you want
// now product points to the property "0"
console.log(product.product_no); // so you can use product.xxx
// or product["xxx"]
} // likewise for "1", "2", "3" and so on
Replace console.log with alert if you do not know what console is.
Each of the product details can be accessed through data[iProductIndex.toString()] member. Data is stored inside data["0"] and data["1"], therefore to access them you need to convert integer value to string. Unfortunately you won't be able to use $.each loop because "0" and "1" are separate member objects. Use for loop with iProductIndex.
Data supplied does not allow for your answer, Salman A. See JSON Arrays for array definition, to have it work your way it must've been defined as
{"products" : [ {"product_no":"1087",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"} ] }
To OP:
alert(data["0"].product_no);
alert(data["1"]["date_of_purchase"]);
try this
<script type="text/javascript">
var json_string={
"logged_in":true,
"firstname":"Joe",
"surname":"Bloggs",
"Full_name":"Joe Bloggs",
"email":"email#website.com",
"phone":"+123456789",
"website":"",
"age":"26-35",
"street":"1 Street Ave",
"city":"Townland",
"state":"NA",
"postcode":"1234",
"country":"Australia",
"products":2,
"0":{
"product_no":"1087",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
},
"1":{
"product_no":"24",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
}
};
for (key in json_string) {
// Most modern browsers should have hasOwnProperty by now.
// This keeps us from getting farther up the chain.
if (json_string.hasOwnProperty(key)) {
document.write(key + "->" + json_string[key]);
document.write("<br>");
}
};
var pro_1= json_string[0]; // here u change 0 with 1 and get the data of "1"
for (key in pro_1) {
if (pro_1.hasOwnProperty(key)) {
document.write(key + "->" + pro_1[key]);
document.write("<br>");
}
};
</script>

Categories

Resources