Split json data using comma - javascript

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.)

Related

Is there a way to replace text from a JSON object after it has been stringified?

I have some JSON data which contains some urls. I'm extracting these urls from the json by looping through the objects which works fine. The urls however have 'page: ' pre-pended to them which i am trying to replace with 'https://'.
I can't get the replace property to work and give me the same result each time.
I've tried using the replace() property in different way and am using the console.log to view my results. I've also tried to stringify the JSON as I hear this is a good thing to do in order to handle it.
Each time i'm still seeing the 'page: ' word and it hasn't been replaced.
function showTopArticles(jsonObj) {
var getEntries = jsonObj.feed.entry;
var stringified = JSON.stringify(getEntries);
console.log(getEntries);
for (var i = 0; i < getEntries.length; i++) {
var list = document.createElement('article');
var articleTitle = document.createElement('li');
var articleUrl = document.createElement('a');
articleTitle.textContent = getEntries[i].title.$t;
articleUrl.textContent = getEntries[i].content.$t;
articleUrl.textContent.replace("page: ", "https://");
console.log(articleUrl.textContent);
list.appendChild(articleTitle)+list.appendChild(articleUrl);
section.appendChild(list);
}
}
I expect the output url to be 'https://www.google.com' but instead im seeing 'page : www.google.com'
replace() returns a modified value, it does not modify the original string.
You want something like:
articleUrl.textContent = articleUrl.textContent.replace("page: ", "https://");

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/

How to insert a json object into an unordered list

I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);

arranging elements in to a hash array

I am trying to break a javascript object in to small array so that I can easily access the innerlevel data whenever I needed.
I have used recursive function to access all nodes inside json, using the program
http://jsfiddle.net/SvMUN/1/
What I am trying to do here is that I want to store these in to a separate array so that I cn access it like
newArray.Microsoft= MSFT, Microsoft;
newArray.Intel Corp=(INTC, Fortune 500);
newArray.Japan=Japan
newArray.Bernanke=Bernanke;
Depth of each array are different, so the ones with single level can use the same name like I ve shown in the example Bernanke. Is it possible to do it this way?
No, you reduce the Facets to a string named html - but you want an object.
function generateList(facets) {
var map = {};
(function recurse(arr) {
var join = [];
for (var i=0; i<arr.length; i++) {
var current = arr[i].term; // every object must have one!
current = current.replace(/ /g, "_");
join.push(current); // only on lowest level?
if (current in arr[i])
map[current] = recurse(arr[i][current]);
}
return join;
})(facets)
return map;
}
Demo on jsfiddle.net
To get the one-level-data, you could just add this else-statement after the if:
else
map[current] = [ current ]; // create Array manually
Altough I don't think the result (demo) makes much sense then.

Is it possible to delete an entry from a JavaScript array?

Is it possible to delete an entry from a JavaScript array? The entry in the list gets replaced with null when delete operator is used.
data = [{pid:30, pname:abc}, {pid:31, pname:def}, {pid:32, pname:zxc}]
delete data[1]
becomes:
data = [{pid:30, pname:abc}, null, {pid:32, pname:zxc}]
FYI I'm getting this as json back from an ajax call. The returned value is parsed like var data = YAHOO.lang.JSON.parse(result.value || '[]')
What about sort()ing and then splice()ing the list?
There are many librarys out there that deal with the serialization and deserialzation of JSON content. Many of those librarys also allow you to manipulate the data from JSON also.
Depending on what language you're using will determine which library you decide to use.
More details would be helpful.
This is a problem with the JavaScript Array class. Deleting a value always leaves a hole. You need to create a new array without the hole. Something like this might be helpful:
Array.prototype.removeItem = function(index){
var newArray = []
for (var i =0; i < this.length; ++i){
if (i==index||typeof this[i] === "undefined") continue;
newArray.push(this[i]);
}
return newArray;
}
var a1 = [1,2,3,4,5]
delete a1[1]
alert(a1.join())
//prints 1,,3,4,5
var a2 = a1.removeItem(3)
alert(a2.join())
//prints 1,3,5 -- removed item 3 and previously "deleted" item 1

Categories

Resources