Create JSON string from javascript for loop - javascript

I want to create a JSON string from a javascript for loop. This is what I tried to do (which gives me something that looks like a JSON string), but it does not work.
var edited = "";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
It gives me this:
"type":"empty","name":"email-address","realname":"Email Address","status":"empty","min":"empty","max":"empty","dependson":"empty",
This does not work if I try to convert it into a JSON object later.

Two problems:
You want an object, so the JSON string has to start with { and end with }.
There is a trailing , which may be recognized as invalid.
It's probably better to use a library, but to correct your code:
Change var edited = ""; to var edited = "{"; to start your JSON string with a {
Add edited = edited.slice(0, -1); after the for loop to remove the trailing comma.
Add edited += "}"; after the previous statement to end your JSON string with a }
Your final code would be:
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
edited = edited.slice(0, -1);
edited += "}";
Again, it's best to use a library (e.g. JSON.stringify) by making an object with a for loop, adding properties by using POST[i].name as a key and POST[i].value as the value, then using the library to convert the object to JSON.
Also, you are starting with index 1 and ending with index POST.length-2, therefore excluding indices 0 (the first value) and POST.length-1 (the last value). Is that what you really want?

//dummy data
var post=[{name:'name1',value:1},{name:'name2',value:2}];
var json=[];
for(var i=0;i<post.length;i++)
{
var temp={};
temp[post[i].name]=post[i].value;
json.push(temp);
}
var stringJson = JSON.stringify(json);
alert(stringJson );
http://jsfiddle.net/3mYux/

You have extra comma in your JSON string. JSON string format: {"JSON": "Hello, World"}
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
// remove last comma:
edited = edited.substring(0, edited.length-1) + "}";

Can't you just build up a hash and do toString on the hash? Something like this:
var edited = {};
for(var i=0;i<POST.length-1;i++) {
edited[POST[i].name] = POST[i].value;
}
Or maybe JSON.stringify is what you are looking for: http://www.json.org/js.html

Related

How to remove all characters before specific character in array data

I have a comma-separated string being pulled into my application from a web service, which lists a user's roles. What I need to do with this string is turn it into an array, so I can then process it for my end result. I've successfully converted the string to an array with jQuery, which is goal #1. Goal #2, which I don't know how to do, is take the newly created array, and remove all characters before any array item that contains '/', including '/'.
I created a simple work-in-progress JSFiddle: https://jsfiddle.net/2Lfo4966/
The string I receive is the following:
ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC
ABCD/ in the string above can change, and may be XYZ, MNO, etc.
To convert to an array, I've done the following:
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
Using console.log, I get the following result:
["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"]
I'm now at the point where I need the code to look at each index of array, and if / exists, remove all characters before / including /.
I've searched for a solution, but the JS solutions I've found are for removing characters after a particular character, and are not quite what I need to get this done.
You can use a single for loop to go through the array, then split() the values by / and retrieve the last value of that resulting array using pop(). Try this:
for (var i = 0; i < currentUserRole.length; i++) {
var data = currentUserRole[i].split('/');
currentUserRole[i] = data.pop();
}
Example fiddle
The benefit of using pop() over an explicit index, eg [1], is that this code won't break if there are no or multiple slashes within the string.
You could go one step further and make this more succinct by using map():
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',').map(function(user) {
return user.split('/').pop();
});
console.log(currentUserRole);
You can loop through the array and perform this string replace:
currentUserRole.forEach(function (role) {
role = role.replace(/(.*\/)/g, '');
});
$(document).ready(function(){
var A=['ABCD','ABCD/Admin','ABCD/DataManagement','ABCD/XYZTeam','ABCD/DriverUsers','ABCD/RISC'];
$.each(A,function(i,v){
if(v.indexOf('/')){
var e=v.split('/');
A[i]=e[e.length-1];
}
})
console.log(A);
});
You could replace the unwanted parts.
var array = ["ABCD", "ABCD/Admin", "ABCD/DataManagement", "ABCD/XYZTeam", "ABCD/DriverUsers", "ABCD/RISC"];
array = array.map(function (a) {
return a.replace(/^.*\//, '');
});
console.log(array);
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(i=0;i<currentUserRole.length;i++ ){
result = currentUserRole[i].split('/');
if(result[1]){
console.log(result[1]+'-'+i);
}
else{
console.log(result[0]+'-'+i);
}
}
In console, you will get required result and array index
I would do like this;
var iur = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC',
arr = iur.split(",").map(s => s.split("/").pop());
console.log(arr);
You can use the split method as you all ready know string split method and then use the pop method that will remove the last index of the array and return the value remove pop method
var importUserRole = ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++;){
var data = currentUserRole[x].split('/');
currentUserRole[x] = data.pop();
}
Here is a long way
You can iterate the array as you have done then check if includes the caracter '/' you will take the indexOf and substact the string after the '/'
substring method in javaScript
var importUserRole = 'ABCD,ABCD/Admin,ABCD/DataManagement,ABCD/XYZTeam,ABCD/DriverUsers,ABCD/RISC';
var currentUserRole = importUserRole.split(',');
for(var x = 0; x < currentUserRole.length; x++){
if(currentUserRole[x].includes('/')){
var lastIndex = currentUserRole[x].indexOf('/');
currentUserRole[x] = currentUserRole[x].substr(lastIndex+1);
}
}

Converting JSON to specific string format

I get the following json data from server.
{"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]}
and i need to convert it to following format:
{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}
I have the following code but not working out:
var cities = "{";
for (var key in data.visits) {
var val = data.visits[key];
//Now you have your key and value which you
//can add to a collection that your plugin uses
var obj = {};
obj[val.City] = '' + val.Count;
var code = '' + val.City;
var count = '' + val.Count;
cities += code + ':' + count + ',';
}
cities += "}";
I need the integers in string representation and need to get rid of the final , .
How can i fix this?
Try this
var data = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
var result = {};
for (var i = 0; i < data.visits.length; i++) {
result[data.visits[i].City] = String(data.visits[i].Count);
}
Example
Keys in object always converts to string you don't need convert it to string manually. If you need convert all object to JSON string you can use JSON.stringify(result);
How I understood you want to create new json with given json.you can parse it,run with cycle on it,and create a new json whatever kind of you want.
here is a link which can help you.
http://www.w3docs.com/learn-javascript/working-with-json.html

JSON.parse error....unexpected token{ from 2nd

My JSON.parse is successful when it is called first. But from 2nd call, unexpected token error occurs.
I found from the search in stackoverflow some explanation for other's question below..
"If you parse it again it will perform a toString-cast first so you're parsing something like "[object Object"] which explains the unexpected token o "
How can i make the fresh parse. my code is like below.
var musicEntry="";
function parsing(){
...
for(var i=0;i<musicList.length;i++){
musicEntry=musicEntry+ '{"fileName":"'+musicList[i].title+'"},';
}
.....
var musicJsonObjString='{"music":['+ musicEntry +']}';
musicJsonObj=JSON.parse(musicJsonObjString);
}
I'd recommend using JSON.stringify() instead of trying to write your own JSON encoder. Whilst your approach might now work with the trailing comma issue fixed, you'll also need to guard against reserved characters in your music title attribute.
Simply build a JavaScript object (or array) and give it to JSON.stringify(obj)
Working example
var musicList = [{
title: 'foo'
}, {
title: 'bar'
}];
var array = [];
for (var i = 0; i < musicList.length; i++) {
array.push({fileName: musicList[i].title})
}
var musicJsonObjString = JSON.stringify({music: array});
var musicJsonObj = JSON.parse(musicJsonObjString);
console.log("music", musicJsonObj);
You need to remove last comma from your array:
var musicJsonObjString='{"music":[' + musicEntry.substr(0, musicEntry.length - 1 ) + ']}';

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/

JSON conversion issue

I am trying (in Javascript an Coldfusion) to convert:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"},
Into this:
{ member,book,journal,new_member,cds}
Notice that I am trying to eliminate quotes.
Is it possible to achieve this? How can I do it?
Ok, so this:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
is JSON.
To convert to a CF struct, you'd go like this:
myStruct = deserializeJSON('{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}');
(Note my examples assume we're operating within a <CFSCRIPT> block.)
Now you've got a simple struct with key/value pairs. But you want a list of the values. So let's make an empty string, then append all the struct values to it:
myList = "";
for (k IN myStruct) {
myList = listAppend(myList,myStruct[k]);
}
Boom. myList should now be "member,book,journal,new_member,cds"
Wrap it in curly braces if you really want to.
myList = "{"&myList&"}";
First of all, I have to thank you for your replies. But some of you have to be more polite with newbies.
var tata = {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
var arr=[]
for (var i in tata) {
arr.push(tata[i])
};
console.log(arr);
wrd = new Array(arr)
var joinwrd = wrd.join(",");
console.log('{' + joinwrd + '}');

Categories

Resources