Converting JSON to specific string format - javascript

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

Related

How to find JSON data at specific index

I want to show only the country name like India,Srilanka etc.
{"result":1,"countries":[
{"country_id":"1","country_name":"Afghanistan"},
{"country_id":"2","country_name":"Albania"},
{"country_id":"3","country_name":"Algeria"},
{"country_id":"4","country_name":"American Samoa"},
{"country_id":"5","country_name":"Andorra"},
{"country_id":"6","country_name":"Angola"},
{"country_id":"7","country_name":"Anguilla"}
]
}
Below I have created JSON object same as yours:
var text = '{"result":1,"countries":[' +
'{"country_id":"1","country_name":"Afghanistan"},' +
'{"country_id":"2","country_name":"Albania"},' +
'{"country_id":"3","country_name":"Algeria"}'+
']}';
var obj = JSON.parse(text);
you can loop through JSON object and get each property value as below:
for(i = 0; i < obj.countries.length ; i++)
{
console.log(obj.countries[i].country_name);
}
Hope This Will Help!
why no iterate the objects and pull that data into a separate array? for example:
[[{"country_id":"1","country_name":"Afghanistan"},{"country_id":"2","country_name":"Albania"},{"country_id":"3","country_name":"Algeria"},{"country_id":"4","country_name":"American Samoa"},{"country_id":"5","country_name":"Andorra"},{"country_id":"6","country_name":"Angola"},{"country_id":"7","country_name":"Anguilla"}]]
.forEach(function(element) {
console.log(element.country_name);
});

Convert into JSON Object

I am trying to convet string into JSON object but with special characters I am not able to convert it:
String looks like when it doesn’t have any special charaters:
Var JsonString = "{"IdKey":"100008000","IdNumber":"50111112","IdType":"Single","IdTitle":"Singel Id","Name":"Nick"}"
And I am doing it like
JsonString = '{"PersonDetails":[' + JsonString + ']}';
var jsonObject = jQuery.parseJSON(JsonString);
Here in JsonObject I am getting an object of array containing object(s) of class detail (Mentioned below).
And I am adding a string PersonDetails because there is a possibility I might get multiple record so I am converting it into an Array. And inside of that array there will be multiple objects of details class.
But sometimes I am getting a string like:
Var JsonString = "{"IdKey":"100008000","IdNumber":"50111112","IdType":"Single","IdTitle":"Single id “VIP”","Name":"Nick"}"
Here IdTitle is: "Single id "VIP""
This also I able to convert into json object by decoding all special characters but in that case I am getting a array of strings not array of Objects of details.
Class details
{
Public string IdKey;
Public string IdNumber;
Public string IdType;
Public string IdTitle;
Public string Name;
}
If you can convert this
var JsonString = "{"IdKey":"100008000","IdNumber":"50111112","IdType":"Single","IdTitle":"Singel Id","Name":"Nick"}";
with double quotes
into
single quotes
var JsonString = '{"IdKey":"100008000","IdNumber":"50111112","IdType":"Single","IdTitle":"Singel Id","Name":"Nick"}';
Then JSON parse will work correctly without any parsing error.
var JsonObject = JSON.parse(JsonString);
Here is the custom function that can handle incorrect JSON and can convert it into a valid/correct JSON object and also you can update this to handle any type of incorrect JSON.
var JsonString = '{"IdKey":"100008000","IdNumber":"50111112","IdType":"Single","IdTitle":"Singel Id "VIP"","Name":"Nick"}'; // Incorrect JSON Object
function convertToJSON() {
var newJsonStringObj = {};
JsonString = JsonString.replace(/["{}]/g, '');
var JsonStringArray = JsonString.split(",");
var arrKey = '';
var arrVal = '';
var JsonStringArrayKeyValue = '';
for(var i=0; i<JsonStringArray.length; i++) {
arrKey = '';
arrVal = '';
JsonStringArrayKeyValue = '';
JsonStringArrayKeyValue = JsonStringArray[i].split(":");
arrKey = JsonStringArrayKeyValue[0];
arrVal = JsonStringArrayKeyValue[1];
newJsonStringObj[arrKey] = arrVal;
}
console.log(newJsonStringObj); // Correct JSON Object
}
convertToJSON();

Loading an array from local storage: result not an array - javascript [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 8 years ago.
I have several large multi-dimensional arrays that I'm saving to local storage. They look like this:
[[[-150],[0],[-650],0],[[-100],[0],[-650],0],[[-50],[0],[-650],0] ... ]
The data is '4D' data. When I try loading this 'string' into an array in another JS (in separate html), it doesn't behave like an array- it's only a string.
Here's how I load the data back into the second JS (not sure why the loop didn't work either):
var lay= new Array();
//for(var g=0;g>=9;g++)
//{ lay[g] = localStorage.getItem("key" + g);
// console.log(lay[g]);
//}
lay[0] = localStorage.getItem("key0");
lay[1] = localStorage.getItem("key1");
lay[2] = localStorage.getItem("key2");
//... more here
lay[9] = localStorage.getItem("key3");
After I load this "4D" info into the array, I pull the info out to use it:
var count=0;
var len=0;
for (y=0;y<=1;y++)
{ console.log(lay[y]);
count=1;
len = lay[y].length;
for (x=1;x<=len-1;x++)
{
Rx = lay[y][count][0];
Ry = lay[y][count][1];
Rz = lay[y][count][2];
Rcolor = lay[y][count][3];
When I add this to the code console.log(len); I get the length of characters in the array, not the number of elements. How can I get the data from local storage to come in and behave like array? I thought that the formatting alone would get it behave like an array.
Do I need to parse it back into an array again? If so, I'm guessing I should just output the data in a simpler format to parse it again...
Thanks for the help!
Edit
Here's how I made the local storage:
for (var a=0;a<=14;a++)
{ updateTemp(tStep + a);
$("#temp tbody tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
rows=ii;
cols=i;
});
});
retval="";
for (var q=0;q<=cols;q++)
{
for (var w=0;w<=rows;w++)
{
var tempv = data[q][w];
var tX = w*50 - 1000;
var tY = 1*50 - 50;
var tZ = q*50 - 1000;
if (tempv==-9){
(dummy=q*w);
}
else {retval += tX +',' + tY + ',' + tZ + ',' + tempv + ',';}
}
}
var kee = "key" + a;
retval = retval.substring(0, retval.length-1); //this is to get rid of the last character which is an extra ,
window.localStorage.setItem(kee, retval);}
JSON encode the array before storing, parse after retrieving.
localStorage.test = JSON.stringify([1,2,3]);
console.log(JSON.parse(localStorage.test));
This is a duplicate of “Storing Objects in HTML5 localStorage”. localstorage only handles strings. As suggested there, serialise your array to a JSON string before storing.

How to parse data in javascript using regex?

How can I use regex in javascript to put items and its values in a array ?
This is my data sample:
battery.voltage: 13.50
battery.voltage.nominal: 12.0
beeper.status: enabled
device.type: ups
driver.name: blazer_ser
driver.parameter.pollinterval: 2
Thanks
use the below code to do that... here variable data contains your data...
data=data.split(/\n+/);
var output={};
for(var i=0;i<data.length;i++){
var a=data[i].split(/:\040+/);
output[a[0]]=a[1];
}
These codes will give you an array like below...
Array (
battery.voltage: "13.50",
battery.voltage: "12.0",
beeper.status: "enabled",
device.type: "ups",
driver.name: "blazer_ser",
driver.parameter.pollinterval: "2"
)
Example:
output['driver.name'] === "blazer_ser"
Why use regular expression, you can simply use substr and indexOf. Assuming you have your list stored in an array you can simply loop through the entries and split on the first occurrence of a colon.
var items = [...]; // Your items.
var arr = {};
for (var i = items.length - 1; i >= 0; i--) {
var key = items[i].substr(0, items[i].indexOf(':'));
var value = items[i].substr(items[i].indexOf(':') + 1).trim();
arr[key] = value;
}
This solution will only work in browsers implementing the trim method. If you want to be on the save side you can overwrite the String.prototype and add the trim method. (See Trim string in JavaScript?)
If you have your items as a string separated by newlines you can easily split it into an array through split;
var list = "battery.voltage: 13.50\n"
+ "battery.voltage.nominal: 12.0\n"
+ "beeper.status: enabled\n"
+ "device.type: ups\n"
+ "driver.name: blazer_ser\n"
+ "driver.parameter.pollinterval: 2";​​
var items = list.split(/\n/);
DEMO
Here's a solution that makes only one pass through the string data using a single regex:
var list = "battery.voltage: 13.50\n"
+ "battery.voltage.nominal: 12.0\n"
+ "beeper.status: enabled\n"
+ "device.type: ups\n"
+ "driver.name: blazer_ser\n"
+ "driver.parameter.pollinterval: 2";
function parse(data) {
var match, result = {};
var pattern = /\s*([^:\s]+)\s*:\s*([^:\s]+)$/gm;
while (match = pattern.exec(data)) {
result[match[1]] = match[2];
}
return result;
}
var test = parse(list);
// dump array
for (var i in test)
console.log(i + ": " + test[i]);
// select one
console.log(test["driver.parameter.pollinterval"]);
Click here to try it out on jsfiddle

Create JSON string from javascript for loop

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

Categories

Resources