Convert into JSON Object - javascript

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();

Related

Json in javascript

i am getting a problem to get json string creating in javascript,
in console log getting pure json string
like
[{"elementId":"selectProduct","elemnetValue":"Y"},{"elementId":"productId","elemnetValue":"415"}]
but when i am storing the output of the json in variable
it change like
[{\"elementId\":\"selectProduct\",\"elemnetValue\":\"Y\"},{\"elementId\":\"productId\",\"elemnetValue\":\"415
"}]
so it can't parse by
JSON.parse(jsonString);
You can use JSON.stringify to get a "parseable" string..
like
var str = JSON.stringify([{"elementId":"selectProduct","elemnetValue":"Y"},{"elementId":"productId","elemnetValue":"415"}]);
var json = JSON.parse(str);
i am done with following code :
var jsonString;
$("#submit").click(function() {
var _intrimForm={
};
var json=[];
var len = document.getElementById("myForm").elements.length;
for(var i=0;i<len;i++){
var _id =document.getElementById("myForm").elements[i].id;
var value = document.getElementById("myForm").elements[i].value;
_intrimForm={
'elementId':_id,
'elemnetValue':value
};
json.push(_intrimForm);
}
console.log(json);
jsonString = JSON.stringify(json);
console.log(jsonString);
readJsonFormElement();
});
function readJsonFormElement()
{
var jsonInterim = new Array();
jsonInterim=JSON.parse(jsonString);
for(var i=0;i<jsonInterim.length;i++)
{
var eId=jsonInterim[i].elementId;
var eValue=jsonInterim[i].elemnetValue;
}
}

How to get json value by string?

I receive the following string from the server response:
var jsonData = '[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]';
I see some jquery plugins can predefine the keys they want
like: index:"firstName", and they get a ul like
<li>Bill</li>
<li>George</li>
<li>Thomas</li>
If index:"lastName", they get a ul like
<li>Gates</li>
<li>Bush</li>
<li>Carter</li>
The only way I know how to parse a json format string is:
var object = JSON.parse(jsonData);
var firstName = object[i].firstName;
var lastName= object[i].lastName;
The plugin pass the index like a parameter
function f(index) {
return object[i].index;
}
How can they achieve this?
Thanks for helping!
You can access object properties with square brackets. JS objects work like arrays in this regard.
var objects = JSON.parse(jsonData),
key = "firstName";
objects.forEach(function (obj) {
var value = obj[key];
// ...
});

Convert Array to objects for Jsondata objects in js

Convert Array-String to Object with Javascript or jQuery
here is my array
data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]
expected output is object
data=[{X:7,Y:12.5},{X:8,Y:15},{X:9,Y:12.5}]
how to do that?
You can try something like this:
var data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
item = item.replace(/{/g, "{\"");
item = item.replace(/}/g, "\"}");
item = item.replace(/:/g, "\":\"");
item = item.replace(/,/g, "\",\"");
return JSON.parse(item);
})
console.log(data)
Try this:
data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.join(',');
data = data.replace(/X/g,'"X"');
data = data.replace(/Y/g,'"Y"');
data = JSON.parse("["+data+"]");
Just convert array to string and do clean up that can be parsed to json.
Simple solution is to replace the X and Y with "X" & "Y". In order to create a string key that can be parse as JSON.
data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]
for(var i in data){
tmp = data[i].replace("X",'"X"').replace('Y','"Y"')
data[i] = JSON.parse(tmp)
}
Enjoy.
var reg = /[^{,]+?(?=:)/g;
var data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
return JSON.parse(item.replace(reg, "\"$&\""));
});

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

AngularJS Convert Array to JSON

I have an array containing 3 elements
var a = [];
a["username"]=$scope.username;
a["phoneNo"]=$scope.phoneNo;
a["altPhoneNo"]=$scope.altPhoneNo;
Now, I want to send this data to server in JSON format. Therefore, I used
var aa = JSON.stringify(a);
console.log("aa = "+aa);
But the console displays empty array
aa = []
How can I convert this array into JSON?
That's not the correct way to add elements to an array, you're adding properties instead.
If you did console.log(a.username); you'd see your $scope.username value.
You could either do
var a = [];
a.push({"username": $scope.username});
a.push({"phoneNo": $scope.phoneNo});
a.push({"altPhoneNo": $scope.altPhoneNo});
But it looks more like what you're trying to do is
var a = {};
a["username"] = $scope.username;
a["phoneNo"] = $scope.phoneNo;
a["altPhoneNo"] = $scope.altPhoneNo;
That is, you want your a to be an object if you're going to add properties to it.
And that would be better written as
var a = {};
a.username = $scope.username;
a.phoneNo = $scope.phoneNo;
a.altPhoneNo = $scope.altPhoneNo;

Categories

Resources