Parsing json jquery - json

My request ajax with json_encode:
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},
{"idHome":"2","Photo":"home2.jpg","Publier":"1"},
{"idHome":"3","Photo":"home3.jpg","Publier":"1"}]
var string = JSON.stringify(data);
var obj = $.parseJSON(string);
console.log(string);
var idHome = obj.idHome;
var photo = obj.Photo;
console.log(obj.idHome);
console.log(obj.Photo);
Problem with parsing json
console log :
[{"idHome":"1","Photo":"home-1.jpg","Publier":"1"},{"idHome":"2","Photo":"home-2.jpg","Publier":"1"},{"idHome":"3","Photo":"home-3.jpg","Publier":"1"}]
undefined
undefined

It is an array so you need to loop through, there are so many ways to do it.
for (i = 0; i < obj.length; i++) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
or:
obj.forEach(function(val) {
console.log(val.idHome);
console.log(val.Photo);
});
or:
for (var i in obj) {
console.log(obj[i].idHome);
console.log(obj[i].Photo);
}
Jquery use :
$.each(obj, function(_, val){
console.log(val.idHome);
console.log(val.Photo);
});
and so on....

Your json is an array of three objects.
Try
console.log(obj[0].idHome);
console.log(obj[0].Photo);
More info:
http://www.w3schools.com/json/json_syntax.asp

Related

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

How to get nested deep property value from JSON where key is in a variable?

I want to bind my ng-model with JSON object nested key where my key is in a variable.
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
Here I want to get value 5 from data JSON object.
I found the solution to convert "course.sections.chapter_index" to array notation like course['sections']['chapter_index'] this. but don't know how to extract value from data now
<script type="text/javascript">
var BRACKET_REGEXP = /^(.*)((?:\s*\[\s*\d+\s*\]\s*)|(?:\s*\[\s*"(?:[^"\\]|\\.)*"\s*\]\s*)|(?:\s*\[\s*'(?:[^'\\]|\\.)*'\s*\]\s*))(.*)$/;
var APOS_REGEXP = /'/g;
var DOT_REGEXP = /\./g;
var FUNC_REGEXP = /(\([^)]*\))?$/;
var preEval = function (path) {
var m = BRACKET_REGEXP.exec(path);
if (m) {
return (m[1] ? preEval(m[1]) : m[1]) + m[2] + (m[3] ? preEval(m[3]) : m[3]);
} else {
path = path.replace(APOS_REGEXP, '\\\'');
var parts = path.split(DOT_REGEXP);
var preparsed = [parts.shift()]; // first item must be var notation, thus skip
angular.forEach(parts, function (part) {
preparsed.push(part.replace(FUNC_REGEXP, '\']$1'));
});
return preparsed.join('[\'');
}
};
var data = {"course":{"sections":{"chapter_index":5}}};
var obj = preEval('course.sections.chapter_index');
console.log(obj);
</script>
Hope this also help others. I am near to close the solution,but don't know how can I get nested value from JSON.
This may be a good solution too
getDeepnestedValue(object: any, keys: string[]) {
keys.forEach((key: string) => {
object = object[key];
});
return object;
}
var jsonObject = {"address": {"line": {"line1": "","line2": ""}}};
var modelName = "address.line.line1";
var result = getDescendantPropValue(jsonObject, modelName);
function getDescendantPropValue(obj, modelName) {
console.log("modelName " + modelName);
var arr = modelName.split(".");
var val = obj;
for (var i = 0; i < arr.length; i++) {
val = val[arr[i]];
}
console.log("Val values final : " + JSON.stringify(val));
return val;
}
You are trying to combine 'dot notation' and 'bracket notation' to access properties in an object, which is generally not a good idea.
Source: "The Secret Life of Objects"
Here is an alternative.
var stringInput = 'course.sections.chapter_index'
var splitInput = stringInput.split(".")
data[splitInput[1]]][splitInput[2]][splitInput[3]] //5
//OR: Note that if you can construct the right string, you can also do this:
eval("data[splitInput[1]]][splitInput[2]][splitInput[3]]")
Essentially, if you use eval on a string, it'll evaluate a statement.
Now you just need to create the right string! You could use the above method, or tweak your current implementation and simply go
eval("data.course.sections.chapter_index") //5
Source MDN Eval docs.
var data = {
"course": {
"sections": {
"chapter_index": 5
}
}
};
var key = "course['sections']['chapter_index']";
var keys = key.replace(/'|]/g, '').split('[');
for (var i = 0; i < keys.length; i++) {
data = data[keys[i]];
}
console.log(data);
The simplest possible solution that will do what you want:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']";
with (data) {
var value = eval(key);
}
console.log(value);
//=> 5
Note that you should make sure key comes from a trusted source since it is eval'd.
Using with or eval is considered dangerous, and for a good reason, but this may be one of a few its legitimate use cases.
If you don't want to use eval you can do a one liner reduce:
var data = {"course":{"sections":{"chapter_index":5}}};
var key = "course['sections']['chapter_index']"
key.split(/"|'|\]|\.|\[/).reduce((s,c)=>c===""?s:s&&s[c], data)

need help recursive javascript function

I want to turn json string
treeNodes =[{managerid:root,Employeeid:01},
{managerid:01,Employeeid:11},
{managerid:01,Employeeid:22},
{managerid:22,Employeeid:33},
{managerid:22,Employeeid:44}];
into this json string using javascript.
json={
id:root,
children[{
id:01,
children[
{id:11},
{id:22}
]},
{
id:22,
children[
{id:33},
{id:44}
]
}
Can someone help with java script function?
I think you need something like this (I assume root is a declared variable):
var rootNode = {Employeeid:root};
var json = makeJsonNode(treeNodes, rootNode);
// Do something with "json"
// ...
function makeJsonNode(treeNodes, node){
var jsonNode = { id : node.Employeeid };
var children = [];
for(var i=0; i<treeNodes.length; i++){
if(treeNodes[i].managerid === node.Employeeid){
children.push(makeJsonNode(treeNodes, treeNodes[i]));
}
}
if (children.length > 0) jsonNode.children = children;
return jsonNode;
}

How convert tsv to Json

I want to make a dynamic graph based on a json file. I have seen many examples with tsv but I donot how to convert it to json.
That is the part that I want to change from tsv to json but I donot know how!
d3.tsv("data/data.tsv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
when I use
d3.json("data/data.json", function(data) {
data.forEach(function d) {
d.date = parseDate(d.date);
d.close = +d.close;
}
});
it gives this error: Uncaught type error: cannot call method 'forEach' of undefined!
Thanks for your suggestions :)
try to do something like this
d3.json("data/data.json", function(data) {
data.forEach(function d) {
d.date = parseDate(d.date);
d.close = +d.close;
}
});
d3.js have support for json, https://github.com/mbostock/d3/wiki/Requests
The syntax around your forEach is a little off; try this instead:
d3.json("data/data.json", function(data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
});
(As Felix points out, this will only work if your JSON object is defined and is an array)
Here a small code where you'll be able to convert tsv to json. It could help you...
ps : here is typescript, but you can easily convert it to vanilla javascript ;)
// Set bunch of datas into format object
tsvToJson(datas: string): Array<Object>{
// Separate each lines
let array_datas = datas.split(/\r\n|\r|\n/g);
// Separate each values into each lines
var detailed_datas = [];
for(var i = 0; i < array_datas.length; i++){
detailed_datas.push(array_datas[i].split("\t"));
}
// Create index
var index = [];
var last_index = ""; // If the index we're reading is equal to "", it mean it might be an array so we take the last index
for(var i = 0; i < detailed_datas[0].length; i++){
if(detailed_datas[0][i] == "") index.push(last_index);
else {
index.push(detailed_datas[0][i]);
last_index = detailed_datas[0][i];
}
}
// Separate data from index
detailed_datas.splice(0, 1);
// Format data
var formated_datas = [];
for(var i = 0; i < detailed_datas.length; i++){
var row = {};
for(var j = 0; j < detailed_datas[i].length; j++){
// Check if value is empty
if(detailed_datas[i][j] != ""){
if(typeof row[index[j]] == "object"){
// it's already set as an array
row[index[j]].push(detailed_datas[i][j]);
} else if(row[index[j]] != undefined){
// Already have a value, so it might be an array
row[index[j]] = [row[index[j]], detailed_datas[i][j]];
} else {
// It's empty for now, so let's say first that it's a string
row[index[j]] = detailed_datas[i][j];
}
}
}
formated_datas.push(row);
}
console.log(formated_datas); // #TODO : remove this
return formated_datas;
}
I transpile and resume Wetteren's code:
convertTSVtoJSON(tsvData) {
const formattedData = tsvData.split(/\r\n|\r|\n/g).filter(e => !!e).map((parsedEntry) => parsedEntry.split("\t"));
const tsvHeaders = formattedData.shift();
return formattedData.map(formattedEntry => {
{
return tsvHeaders.reduce((jsonObject, heading, position) => {
jsonObject[heading] = formattedEntry[position];
return jsonObject;
}, {});
}
});
}

Read list from json object

I am try to read list from json here id my code:-
List<EmailProvider> list = new List<EmailProvider>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/WidgetXml.xml"));
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//widget");
foreach (XmlNode node in nodes)
{
EmailProvider obj = new EmailProvider();
obj.Name = node["Name"].InnerText;
obj.left = Convert.ToInt32(node["left"].InnerText);
obj.Id = node["id"].InnerText;
obj.IsVisible = Convert.ToBoolean(node["isActive"].InnerText);
long s = Int64.Parse(node["top"].InnerText);
obj.top = s;
obj.desc = node["desc"].InnerText;
list.Add(obj);
}
var result = list.OrderBy(p => p.IsVisible).ToList();
return result.ToArray();
and on view:-
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
alert(data.length);
var st = JSON.stringify(data);
alert(st.length);
});
});
length always show 54 but in array only 4 items. How can i read all recors from array by json from json object.
Thanks in advance.
Try returning a JsonResult from your controller method, using the controller method Json
var result = list.OrderBy(p => p.IsVisible).ToList();
return Json(result.ToArray());
On JavaScript, you should just need to iterate over the array as in:
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
for(var i = 0;i < data.length; i++){
alert(data[i].Name);
}
});
});