Json in javascript - 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;
}
}

Related

Get JSON stringify value

I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?
This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}
Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}
you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);
instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array

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, "\"$&\""));
});

Pass Python array to javascript?

I'm new to HTML/javascript. I'm running a local server, with an html/javascript file and a separate python script.
Question: How do I pass a python array to javascript variable?
Work so far:
I've written the array to file data.txt:
1 32.1
2 10.0
but I could put it in JSON format if it's easier.
Here's my progress so far:
var x_pos = [];
jQuery.get('http://127.0.0.1:8000/data/data.txt',function(data){
// ??? Code here ???
});
console.log(x_pos[0])
Note: if there is a much simpler way to do this, I'm open to suggestion. Thanks.
var x_array = [];
var y_array = [];
jQuery.get('http://localhost/test/data.txt',function(data){
var lines = data.split(/\r\n|\n/g);
for (var i = 0; i < lines.length; i++) {
line = lines[i].split(/\s+/g);
x_array.push(line[0]);
y_array.push(line[1]);
}
console.log(x_array);
console.log(y_array);
});
Use JSON instead. Then you can just parse it as
jQuery.get('http://localhost/data.txt', function(data) {
var xy = JSON.parse(data);
});
and use as
alert(xy['1']); // or xy.propertyname if it is not-numeric
Your data structure would be like
{
"1": 32.1,
"2": 0
}
Just create a json structure for this and do a JSON.parse(data) after.
Here is your structure:
{x: [1,2,3,4], y:[32.1,10.0,76.3]}
One of the solutions is use split. It splits the string.
var newData = [];
data = data.split('\n');
data.forEach(function(entry){
entry = entry.split(' ');
newData.push({
x : entry[0],
y : entry[1]
});
});
console.log(newData);
You need to use regular expressions to parse the text file. You cannot just use JSON.parse() on a string that isn't in json format.
http://plnkr.co/edit/39aBGgwvNI7Lem6eiefu?p=preview
$.get("http://localhost/data.txt", parse);
function parse(str) {
var lineBreak = /\r\n/g;
var space = /\s/g;
var tmp = str.split(lineBreak).map(function(l) {
var split = l.split(space);
return { key: split[0], val: split[1] };
});
var data = JSON.stringify(tmp, null, 2);
$("#data").text(data);
}

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

Access to a certain part of JSON data with jQuery

So i have this JSON:
{
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
}
I just want to access to the fields names
id_u,_nombre_usuario,apellido_paterno_usuario
And then, create an array with that info.
How can i do that?
Thanks guys
Do this way :
var keyValuePair = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
var arr =new Array();
for (key in keyValuePair){
arr.push(key); // for keys
// arr.push(keyValuePair[key]); // for values
}
Use .each() to parse JSON.
Try this:
var keyArray = [];
var a = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
$.each(a,function(i,v){
keyArray.push(i); // i is json key and v is json value.
});
console.log(keyArray);
DEMO
Object.keys(jsonObject) is enough.

Categories

Resources