Print a JSON data with Javascript - javascript

I have the following JSON.
{
"lang": [
{
"SECTION_NAME": {
"english": "My title"
},
"SECTION_NAME_2": {
"english": "My title"
}
}
]
}
And I'm looking to print the value like this:
$.getJSON('json/lang.json', function(data) {
var text = data['lang']['SECTION_NAME'];
$('#title').html(text.english);
});
But I have the following error:
TypeError: undefined is not an object (evaluating 'text.english')
Any help please.
Thanks.

You have to access it via index as lang is an array of object
like this
console.log(data['lang'][0]['SECTION_NAME'])
JSFIDDLE

The value of lang is an array which contains an object.
You are ignoring the array and trying to access the objects as if it was the value of lang directly.

Related

Get values of object from .map in React

I'm currently working with react to read and display the elements given in a json file.
As far as this, everything works fine. Now I want to display a text in a label of a checkbox which should also be able to contain links without turning the whole label in a link.
To do this I made this json structure:
"labels": [
"Text without a link",
{
"url": "google.de",
"label": "Link text"
}
]
And to display these side by side I'm mapping over the json Array "labels"
labels: Array<Object>;
labels.map(el => {
if (isString(el))
return el;
else
return <Link href={el['url']} color="inherit">{el['label']}</Link>
})
But I can't access el['url'] or el['label'].
It throws:
"Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Object'."
Probably I'm just overseeing something unbelievable simple. Help would be nice!
Cheers,
m3_
Try this:
return <Link href={el.url} color="inherit">{el.label}</Link>
Try this
var data = {
"labels": [
"Text without a link", {
"url": "google.de",
"label": "Link text"
}
]
}
const links = data.labels.map(item => {
if(isString(item)) {
return item
}
const { url, label } = item
return <Link href={ url } color="inherit">{ label }</Link>
})
"labels": [
"Text without a link",
{
"url": "google.de",
"label": "Link text"
}
]
here, labels is an array which has values of type string and object. For strings it wont have url and label properties. So while parsing every value using map function, you have to check the type of value is object or not. If it is an object then only check url and label for it.

How to get a value from a nested object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I am getting below sample json data as input,
var JSONDATA =
{
"MainNode": {
"_attributes": {
"class": "ABC",
"projectclass": "MyProject",
"prjname": "PrjName",
"enabled":"true"
},
"PrjProp": {
"_attributes": {
"name": "MyProject.save"
},
"_text": true
}
}
}
Using Jquery or Javascript, I want to get the "projectclass" value in first "_attributes". There could be multiple "_attributes" in JSON object but the requirement to the "projectclass" (fixed) from the first (fixed) "_attributes" only.
This can be achieved like,
console.log(JSONDATA.MainNode._attributes.testclass);
but "MainNode" is not fixed, this can be "OtherNode". So how to handle this is variable ? I tried , console.log(Object.keys($scope.testplan)[0]); which shows main node name but how to use this in console.log(JSONDATA.MainNode._attributes.testclass); as variable ?
Please suggest.
Thanks
You have to access as JSONDATA.MyProject._attributes.projectclass
Using [0] is accessing the first element of an array. This is an object, so that is the reason why you are not able to access JSONDATA[0][0].projectclass
var JSONDATA = {"MyProject":{"_attributes":{"class":"ABC","projectclass":"MyProject","prjname":"PrjName","enabled":"true"},"PrjProp":{"_attributes":{"name":"MyProject.save"},"_text":true}}};
console.log( JSONDATA.MyProject._attributes.projectclass );
And there is going to be only 1 _attributes under MyProject.
If you have multiple projects, You can loop by:
var JSONDATA = {
"MyProject":{"_attributes":{"class":"ABC","projectclass":"MyProject","prjname":"PrjName","enabled":"true"},"PrjProp":{"_attributes":{"name":"MyProject.save"},"_text":true}},
"MyOtherProject":{"_attributes":{"class":"ABC","projectclass":"MyOtherProject","prjname":"PrjName","enabled":"true"},"PrjProp":{"_attributes":{"name":"MyProject.save"},"_text":true}}
};
for ( var key in JSONDATA ) {
console.log( JSONDATA[key]._attributes.projectclass );
}
you cant use JSONDATA[0][0] to acces a JSON object
for example data is your JSON object to access projectclass simply
data={
"MyProject": {
"_attributes": {
"class": "ABC",
"projectclass": "MyProject",
"prjname": "PrjName",
"enabled": "true"
},
"PrjProp": {
"_attributes": {
"name": "MyProject.save"
},
"_text": true
}
}
}
console.log(data.MyProject._attributes.projectclass);

set json property depending on child property

I am creating this JSON object
{
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"image_aspect_ratio": "square"
"elements": [
new CreateBallon(results[rand])
]
}
}
}
I want to set the image_aspect_ratio in only if elements[0].someProp is present.
How can I do that?
Let's clear what JSON is. It is a textual notation for data. If you do anything with the object that involves code of Javascript don't call it JSON so, The object you're talking about is not a JSON but a JavaScript object created via object literal notation.
Now to answer your query, you can't refer to this object before you've fully initialized that object. So what you can do is initialize your object with some default value and then you should be able to edit any property based on the properties from the same object. Something like
var obj = {"property1" : "X", "property2" : ""};
Now you can update your object like
obj.property2 = obj.property1 =='yourCondition' ? 'NewValue' : obj.property2

Javascript (Appcelerator Titanium) Multidimensional Array parse doesn't work

I have an problem with the parsing of an multidimensional array, i get this from facebook as an answer:
In e.result i have this:
{
"data":[
{
"name":"Linda Kase",
"id":"1393034660999695"
},
{
"name":"Dick Typ",
"id":"1376046576034204"
},
{
"name":"a a",
"id":"1388801108093951"
},
{
"name":"b b",
"id":"1382328532076389"
}
],
"paging": {
"next":"https:\/\/graph.facebook.com\/v2.2\/1378163649155341\/friends?format=json&access_token=XXXXXXXXXXXXXXXXXXX"
},
"summary":{
"total_count":8
}
}
and this is my code to parse it:
Ti.App.fb.requestWithGraphPath('me/friends',false, 'GET', function(e){
if(e.success){
var result = e.result;
alert(result.data[0].name);
}
});
I always recieve this:
Uncaught TypeError: Cannot read property '0' of undefined
Anyone an idea why it isn't working ? I've also tried to JSON.stringify and JSON.parse the e.result
Thank you!
You have to use:
var result = JSON.parse(e.result);
alert(result.data[0].name);
because you get it as a string, not as an array

Unable to get the right json property dynamically

I have following JSON structure:
var pages = {
"yearly": {
"MXN": {
"id" : "2c92c0f940f1b6e50140f4b7d9054a6e",
},
"NZD": {
"id" : "2c92c0f940f1b6d40140f4b7e14d66b7",
}
},
"monthly": {
"MXN": {
"id" : "2c92c0f940f1b6d40140f4b40ed85c57",
},
"NZD": {
"id" : "2c92c0f840f1c2cc0140f4b3b15d3956",
}
}
}
i want to get the values of json inside yearly property dynamically for example i get the dynamic value MXN inside a variable currency now i am having problem in accessing its value i am trying to access it like this:
pages.yearly[currency].id
but i am unable to get to that id property gives me error of TypeError: pages.monthly[currency] is undefined what is wrong in my syntax that is causing type error??
The according to this error the variable currency needs to be defined. For example
var currency = "MXN";

Categories