Javascript: parse json to list - javascript

I am new to javascript, sorry for silly question and possible duplicate. Please suggest me efficient way of parsing json. I would like to fetch list of strings Maktg:
{
"d":{
"results":[
{
"Maktg":"BATTERY",
"W":"1000",
"IS":"",
"IM":"",
"IW":"",
"__metadata":{
"type":"s",
"uri":"https://some_url)"
},
"IMaktg":"",
"Matnr":"0001",
"Stlan":"1"
},
{
"Maktg":"CONTROL",
//etc...

We have a JSON:
{
"d":{
"results":[
{
"Maktg":"BATTERY",
"W":"1000",
"IS":"",
"IM":"",
"IW":"",
"__metadata":{
"type":"s",
"uri":"https://some_url"
},
"IMaktg":"",
"Matnr":"0001",
"Stlan":"1"
}
]
}
}
Lest convert string JSON into more useful JavaScript object:
The JSON.parse() method parses a string as JSON, optionally
transforming the value produced by parsing.
var
jsonStr = '{"d":{"results":[{"Maktg":"BATTERY","W":"1000","IS":"","IM":"","IW":"","__metadata":{"type":"s","uri":"https://some_url"},"IMaktg":"","Matnr":"0001","Stlan":"1"}]}}';
jsonObj = JSON.parse(jsonStr),
results = jsonObj.d.results;
for (var i in results) {
console.log(results[i]['Maktg']);
/*
results[i]['W']
results[i]['IS']
results[i]['IM']
results[i]['__metadata']['type']
and etc...
*/
}

Try this:
var jsonArray = yourJSON.d.results;
var results = [];
jsonArray.forEach(function(object){
results.push(object.Maktg);
}
console.log(results);

Please try to get output with JSON.parse like this.
var getData = JSON.parse(data);
for(i=0;i<getData.d["results"].length;i++)
{
alert(getData.d["results"][i].Maktg);
alert(getData.d["results"][i].W);
//etc...
}

Related

Adding nested arrays in JSON file using node.js

I am fairly new to Javascript and nodejs. I would like a JSON file (results.json) that takes the format of something similar to this:
Starts off as:
{
"name":"John",
"task":[]
}
then eventually becomes something like this with nested arrays:
{
"name":"John",
"task":[ ["task1","task2"], ["task3", "task4"] ]
}
I want to push to the "task" array a new list of tasks (always of size 2) everytime something is done (in my case when a form is submitted with a button-press).
So for example, after another "action", the JSON file will look something like this:
{
"name":"John",
"task":[ ["task1","task2"], ["task3", "task4"] , ["task5", "task6"] ]
}
NOTE: "task(1,2,...,6) was just used as an example, these will be other strings corresponding to the form submission.
This is what I have so far in my server-side file:
var fs = require('fs')
app.post("/addtask", function(req, res) {
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
var newTask1 = req.body.newtask1
var newTask2 = req.body.newtask2
//WHAT DO I PUT HERE
fs.writeFile("results.json", JSON.stringify(json))
})
});
Please do correct me if my syntax is wrong or if my idea of how a JSON file works is wrong.
Just push the data as an array
var resObj= {
"name":"John",
"task":[]
}
var newTask1 = "task1";
var newTask2 = "task2";
resObj.task.push([newTask1,newTask2]);
console.log(resObj);

AJAX - Parse JSON object returned in JQUERY

I stucked a little bit in here>
My php script returns this JSON (in variable response) (encoded array with json_encode) :
{"1":{"id":"pvv001","tooltip":"tip1","link":"http:\/\/domain\/file1.html"},"2":{"id":"pvv002","tooltip":"tip2","link":"http:\/\/domain\/file2.html"}}
I hope this is valid JSON object ...
Then here is JavaScript function which should get this string and process it - load to ELEMENT "id" a content of "link".
function jLinks(idchapter)
{
var url = 'ajax_loadlinks.php';
var data = {
idchapter : idchapter
};
$.post(url,data, function(response)
{
//$('#coursecontent').html(response);
var obj = JSON.parse(response);
for (var i=0; i<obj.length; i+1)
{
$('#'+obj[i].id).html('link');
}
});
}
It is not throwing any error in browser or console, but elements are not updated at all.
I quess my parsing and accessing data is wrong somehow, but I have no idea how to debug.
As your string is an object not array, so you need $.each method to loop over each key of object.
var obj ={
"1": {
"id": "pvv001",
"tooltip": "tip1",
"link": "http:\/\/domain\/file1.html"
},
"2": {
"id": "pvv002",
"tooltip": "tip2",
"link": "http:\/\/domain\/file2.html"
}
};
$.each(obj,function(i,v){
$('#'+v.id).html('link');
});
Fiddle
please try this
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(obj[prop].id);
$('#'+obj[prop].id).html('link');
}
}

aAccessing key values in JSON

I have a JSON response like this. I want to access the rollbacktoken key. How should I do it ?
{"query":{
"pages":{
"5":{
"pageid":5,
"ns":0,
"title":"Abhishek",
"revisions":
[{
"revid":376,
"parentid":360,
"user":"Abhishek",
"timestamp":"2015-02-15T10:29:55Z",
"comment":"",
"rollbacktoken":"232e77d570434db159dbbd3d43d3ea4e+\\"
}]
}
}
}
}
I have tried:
var a = JSON.stringify(query.pages.revisions.rollbacktoken);
figured it out
var json = JSON.parse(data);
console.log(json.query.pages['5'].revisions['0'].rollback);
var json = JSON.parse(data);
json.getJSONObject("query").getJSONObject("pages")..getJSONObject("5").getJSONObject("revisions").rollbacktoken;

Looping through a json object in javascript

I am trying to look through an object, but based on the structure I do not know how to get to the data.
Object:
{
"177":{
"text":"test text",
"user_name":"Admin",
"date":"1385494358",
"docs":{
"document_name": [
"marketing_service",
"maintenance_service",
"development_service"],
"document_type":[
"png",
"png",
"png"]
}
},
"174":{
"text":"Some more images",
"user_name":"Admin",
"date":"1385493618",
"docs":{
"document_name": [
"marketing_service16",
"maintenance_service53"],
"document_type":[
"png","png"]
}
}
}
The loop I am attempting in jQuery
var obj = $.parseJSON(data);
$(obj).each(function(index, note) {
console.log(note.text + note.user_name + note.date_created);
});
It is returning undefined. What am I doing wrong?
Try like this
var obj = $.parseJSON(data);
for(var n in obj){
var note = obj[n]
console.log(note.text + note.user_name + note.date_created);
}
To loop through a json object just use a for loop.
The way you are doing it will return errors because it is trying to select that json object from the page which does not exist.
Sample code:
var obj = $.parseJSON(data); //assuming `data` is a string
for(index in obj) {
var note = obj[index];
console.log(note.text + note.user_name + note.date_created);
};
its a little better to do it like this:
$.each(obj, function ( index, note ) {
console.log( note.text + note.user_name + note.date_created );
});
this should give you what you need
Working Demo: http://jsfiddle.net/gZ7pd/ or for document http://jsfiddle.net/NGqfB/
Issue is parseJson on the object which is Json.
in the demo above the var obj = $.parseJSON(data); returns null, if I use data it will work.
Hope this helps ;)
Code
var data = {
"177":{
"text":"test text",
"user_name":"Admin",
"date":"1385494358",
"docs":{
"document_name": [
"marketing_service",
"maintenance_service",
"development_service"],
"document_type":[
"png",
"png",
"png"]
}
},
"174":{
"text":"Some more images",
"user_name":"Admin",
"date":"1385493618",
"docs":{
"document_name": [
"marketing_service16",
"maintenance_service53"],
"document_type":[
"png","png"]
}
}
};
var obj = $.parseJSON(data);
alert(obj)
$.each(data,function(index, note) {
alert(note.text + note.user_name + note.date_created);
});

How to read JSON array in jQuery

I am using jQuery .load() function to load the results from server and append it in my html:
$("#content").load('Get/Information?class=Arts&min=1',
function (responseText, textStatus, XMLHttpRequest) {
console.log(responseText);
// parseJSON(responseText);
});
In my controller I tried converting my jagged array from the model into a json object and then send it to the client:
public JsonResult GetInformation(string class, int min){
var stdObj = new Student();
string[][] information = stdObj.GetInformation(class, min);
return Json(information, JsonRequestBehavior.AllowGet);
}
And after this when I check the response through console.log(responseText);
I have a jSon like string in the following format:
[
["93","Title-1","http://stackoverflow.com"],
["92"," Title-2","http://stackoverflow.com"],
["90"," Title-3","http://stackoverflow.com"],
["89"," Title-4","http://stackoverflow.com"],
["89"," Title-5","http://stackoverflow.com"],
null,null,null,null,null]
I am not sure if this a proper jSon, as from what I learn jSon is in name: value pairs, but here there are only values, considering this how can I read this string/array and print in following manner:
This just a representation(pseudo code) of how I required it to be handled:
for(int 1=0; i<response.length();i++){
$("#content").html('<h1>'+i.Id+'</h1>'+'<p>'+i.Title+'</p>'+'<span>'+i.url+'</span>')
.slideDown('slow');
// $("#content").html('<h1>39</h1>'+'<p>Title-1</p>'+'<span>http://stackoverflow.com</span>');
}
Use var dataArray = jQuery.parseJSON(response);
If your response array is
myArray =
[
["93","Title-1","http://stackoverflow.com"],
["92"," Title-2","http://stackoverflow.com"],
["90"," Title-3","http://stackoverflow.com"],
["89"," Title-4","http://stackoverflow.com"],
["89"," Title-5","http://stackoverflow.com"],
]
you can use
for(int i=0; i<myArray.length();i++)
{
$("#content").html('<h1>'+myArray[i][0]+'</h1>'+'<p>'+myArray[i][1]+'</p>'+'<span>'+myArray[i][2]+'</span>').slideDown('slow');
}
Demo: http://jsfiddle.net/KX596/1/
You need to use getJSON()
$.getJSON('Get/Information?class=Arts&min=1', function (response) {
$.each(response, function(idx, rec){
$("#content").append('<h1>'+rec.Id+'</h1>'+'<p>'rec.Title+'</p>'+'<span>'+rec.url+'</span>').slideDown('slow');
})
});
$.getJSON('Get/Information', { class: "Arts", min: 1 })
.done(function( json ) {
$.each(json , function(i, v) {
var id = v[0]; // etc
});
});
Refer to getJSON

Categories

Resources