The JSON file I have is following:
{
"root": {
"Quizsize": null,
"{urn:abc.com/xmlns/mona/page}page": [
{
"#xid": "page1623",
"#title": "Quiz Landing Page",
"{urn:abc.com/xmlns/mona/page}comment": null,
"{urn:abc.com/xmlns/mona/page}skills": null,
"{urn:abc.com/xmlns/mona/page}info": {
"{urn:abc.com/xmlns/mona/common}property": {
"#name": "quiz_landing",
"#value": "true"
}
}
}
]
}
}
}
I am loading this JSON file using :
var jsondata = eval("("+chapterRequest.responseText+")") ;
Root = jsondata.root
Now I want to access #xid which is "page1623 and #name which is "quiz_landing". I dont know how to do this,Please help.
Thanks
JSON.parse(x) is better than eval(x), for one. It is not supported natively by some browsers though. If you want to access #xid, "urn:abc.com/xmlns/mona/page}page" points to an array whose first element is an object.
So use Root["{urn:abc.com/xmlns/mona/page}page"][0]["#xid"]. Or mix bracket and dot notation. Your choice, really.
When the key isn't a valid identifier, you use object['key'] instead of object.key, so jsondata.root['{urn:abc.com/xmlns/mona/page}page'][0]['#xid'].
Related
I need to access arrays inside JSON object and save into different arrays. I tried few ways but no luck.
I could get all other values without any problem but when it comes to arrays I couldn't retrieve those.
I feel the way I try to access arrays inside JSON object might be wrong and but I couldn't figure it out
Here is JSON object
{
"packId":51,
"shortCode":"TTY",
"packDescription":"TTY Des",
"startDate":"2020-09-01",
"endDate":"2020-09-08",
"validityValue":30,
"validityType":"Hours",
"expiryAction":true,
"expirySMS":64,
"activationSMS":64,
"deactivationSMS":64,
"subscriptionSMS":0,
"deactivationAction":true,
"deactivationShortCode":"DEACT TTY",
"deprovisionOnExpiry":true,
"deleteByPackType":true,
"packType":{
"packTypeId":2,
"name":"Facebook"
},
"timeBands":[
{
"timeBandId":1,
"start":"8:00",
"end":"23:00",
"timeBand":"8:00-23:00"
},
{
"timeBandId":2,
"start":"8:00",
"end":"20:00",
"timeBand":"8:00-20:00"
}
],
"activationTypes":[
{
"activationTypeId":1,
"name":"SMS"
},
{
"activationTypeId":2,
"name":"Web"
}
],
"channels":[
{
"channelId":1,
"name":"hShenid"
},
{
"channelId":2,
"name":"Genesis"
}
],
"users":[
]
}
Axios Call
getPackById(id)
{
return axios.get(`${API_URL}/pack/get/${id}`);
}
refreshPack()
{
PackComposeDataService.getPackById(this.id).then((res)=>
{
//I can access these values without any problem
this.deleteByPackType= res.data.deleteByPackType,
this.packTypeValues=res.data.packType,
this.shortCode= res.data.shortCode,
this.packDescription= res.data.packDescription,
this.startDate= res.data.startDate,
this.endDate= res.data.endDate,
this.subscriptionSMS= res.data.subsNotificationValues["id"],
this.validityValue= res.data.validityValue,
this.validityType= res.data.validityType,
this.actionOnExpiry= res.data.expiryAction,
this.expirySMS= res.data.expiryNotificationValues,
this.activationSMS= res.data.activationNotificationValues,
this.deactivationAction= res.data.deactivationAction,
this.deactivationShortCode= res.data.deactivationShortCode,
this.deactivationSMS= res.data.deactivationNotificationValues,
this.deprovisionOnExpiry= res.data.deprovisionOnExpiry,
//I need to get these arrays
this.timeBandValues= res.data.timeBands,
this.activationTypes= res.data.activationTypes,
this.channels= res.data.channels,
this.users= res.data.users
});
I understand you want to take only the timeBand string of each of the arrays (or the activationType, eventually).
If that's the case, you may want to map to convert each object in the array to a simple string:
// ...
this.timeBandValues = res.data.timeBands.map(o => o.timeBand) // you're going to get ["8:00-23:00", "8:00-20:00"]
// ...
I am trying to access the value of a variable present inside a script tag. But I am not able to retrieve the value. I tried in few ways but I don't get the expected result.
I need to get the values and parse and do some operations over it but I am blocked from morning can u please some one help me it's ruining my time.
var scriptTag = document.getElementsById('test');
console.log(scriptTag.window["ytInitialData"]); //shows undefined
console.log(scriptTag.getAttribite(window["ytInitialData"])); // shows null
<script id="test">
window["ytInitialData"] = {
"responseContext": {
"serviceTrackingParams": [{
"service": "GFEEDBACK"
}]
}
};
window["ytInitialPlayerResponse"] = {
"responseContext": {
"serviceTrackingParams": [{
"service": "GFEEDBACK"
}]
}
};
if (window.ytcsi) {
window.ytcsi.tick("pdr", null, '');
}
</script>
The window object is global and can be accessed from any script on your page, so set the window property like this:
window.ytInitialData = {
"responseContext": {
"serviceTrackingParams": [{
"service": "GFEEDBACK"
}]
}
}
"ytInitialData" is a string literal so you can use dot notation instead of brackets.
Then access it again anywhere later in your script the same way:
console.log(window.ytInitialData)
window.ytInitialData = {
"responseContext": {
"serviceTrackingParams": [{
"service": "GFEEDBACK"
}]
}
}
console.log(window.ytInitialData)
I am beginner in Javascript/jQuery and I am working on an interface made with KnockoutJS, so I have several models. I would like to save all the data in the database but I don't know how to do it.
I started with :
self.save = function() {
var data = ko.toJS(self);
var test = ko.toJSON(self);
console.log(test);
}
$.ajax({
url: "myURL",
data: {'carrier': data.carrier},
type: "POST",
});
and this is the result of the console.log :
{"id":1,"carrier":"1","Settings":[{"id":1,"price":{"id":1,"DeliveryStandard":"3.00","DeliveryExpress":"6.00","Details":{"id":1,"Standard":[{"id":1,"fromPrice":0,"maxPrice":"45.000"}],"Express"[{"id":1,"fromPrice":0,"maxPrice":"66.000"}]}}}}]}
I can get the value of carrier by using data.carrier but I don't know how to get the other data like DeiveryStandard, DeliveryExpress, fromPrice, maxPrice ...
Have you got an idea?
Thanks you in advance, and sorry if my question is silly!
If you format your JSON into a more readable format, with indenting, it makes it a lot easier to understand:
(though it should be noted that it is only technically JSON while in a string format, outside of that it is just a standard javascript object)
{
"id":1,
"carrier":"1",
"Settings":[
{
"id":1,
"price": { "id":1,
"DeliveryStandard":"3.00",
"DeliveryExpress":"6.00",
"Details": { "id":1,
"Standard": [{"id":1,
"fromPrice":0,
"maxPrice":"45.000"
}],
"Express" //Missing semi-colon
[{"id":1,
"fromPrice":0,
"maxPrice":"66.000"
}]
}
}
}}//One too many closing braces
]
}
First thing to note is you have 2 syntax errors, highlighted above with comments. So fix them first! (Though I wonder if they are typos as you seem to have it working at your end)
Then we can look at the structure tree to work out where the values you want are...
DeiveryStandard and DeliveryExpress are both properties of an object assigned to price, which it a property of the first item in the Settings array. So you can access them like so:
var DeliveryStandard = data.Settings[0].price.DeliveryStandard;
var DeliveryExpress= data.Settings[0].price.DeliveryExpress;
fromPrice and maxPrice are found multiple times, in both Standard and Express items. So you need to decide what version you need. If you want Standard then you can get the first item of the Standard array like so:
var standardObject = data.Settings[0].price.Details.Standard[0];
Which you can then access the properties of like:
var fromPrice = standardObject.fromPrice;
var maxPrice = standardObject.maxPrice;
I am sure you can work out how to get the Express version of the same data!
From what you seem to have been able to work out on your own, I think your problem is not knowing how to deal with the arrays. Note that arrays are defined with square brackets [], and elements within an array should be accessed with a zero-based index, for example: array[0] for the first element, and array[1] for the second element.
This should work.
console.log(data.Settings[0].price.DeliveryStandard);
Fixed some errors in your JSON.
var j = {
"id" : 1,
"carrier" : "1",
"Settings" : [{
"id" : 1,
"price" : {
"id" : 1,
"DeliveryStandard" : "3.00",
"DeliveryExpress" : "6.00",
"Details" : {
"id" : 1,
"Standard" : [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "45.000"
}
],
"Express": [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "66.000"
}
]
}
}
}
]
};
alert(j.Settings[0].price.DeliveryStandard);
alert(j.Settings[0].price.DeliveryExpress);
alert(j.Settings[0].price.Details.Standard[0].fromPrice);
alert(j.Settings[0].price.Details.Standard[0].maxPrice);
here I have a declaration:
<div id="timeline-embed"></div>
<script type="text/javascript">
var timeline_config = {
width: "100%",
height: "100%",
debug: true,
rows: 2,
source: 'Timeline/example_json.json'
}
</script>
<script type="text/javascript" src="Timeline/compiled/js/storyjs-embed.js"></script>
so now I want to instead source: 'Timeline/example_json.json' to use
something like:
source: '{
"timeline":
{
"headline":"Sh*t People Say",
"type":"default",
"text":"People say stuff",
"startDate":"10/4/2011 15:02:00",
"date": [
{
"startDate":"10/4/2011 15:10:00",
"endDate":"10/4/2011 15:55:00",
"headline":"prvo",
"text":"<p>dddddddddddddddd dd</p>",
"asset":
{
"caption":"yessss"
}
},
{
"startDate":"10/4/2011 17:02:00",
"endDate":"10/4/2011 18:02:00",
"headline":"drugo da da",
"text":"<p>In true political fashion, his character rattles off common jargon heard from people running for office.</p>",
"asset":
{
"media":"http://youtu.be/u4XpeU9erbg",
"credit":"",
"caption":""
}
}
]
}
}'
but doesn work. I really dont know what is probem exactly... Please help.
So this is verite Timeline plugin and this plugin need JSON as source, but is there any way to change source with Javascript variable?
The way you have this written, the value of "timeline_config.source" is a String, not a "usable" Javascript object.
You may need to convert the string to an object using JSON.parse(). So add this line of code as the last line of your first < script > block.
timeline_config.source = JSON.parse(timeline_config.source)
Alternatively, as pointed out in the comments, you can simply remove the single quotes around the string, and it will natively by a JS Object.
Try removing the ' string delimiter, so it says
source: {
"timeline": { ... }
},
This way it is a JS object and not a string.
I'm unable to successfully get data from the JSON string below. Using JavaScript, I'm able to alert the full string [ alert(data); ] but I'm unable to get only the first name.
Can someone please help?
var data = {
"name": [
"Enid Norgard",
"Cassie Durrett",
"Josephine Ervin"
],
"email": [
"TheWoozyGamer#gmail.com",
"TheHabitualGamer#gmail.com",
"TheUptightGamer#gmail.com"
],
"role": [
"Gamer",
"Team Leader",
"Player"
],
"emp_id": [
"50",
"408",
"520"
],
"id": [
"234",
"444",
"235"
]
}
Looks like you have a string(because when you use alert the complete text is shown, if it was a object then [Object object] would have shown), first you need to parse it using JSON.parse()
var t = JSON.parse(data)
alert(t.name[0])
Note: Old browsers like IE8 which does not have native support for JSON you have to add a library like json2 to add JSON support
use the following code
alert(data.name[0]);
//sample code
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
Most browsers support JSON.parse(), hope this will help you for detail see link.
With data.name[0] you will get the name Enid Norgard
Similar to that use
data.name[index]
while index is the position of the name in the innerarray.
If you want only the names array use:
alert(data.name)
try this to loop through all elements
for(x in data)
{
for(y in data[x])
{
alert(data[x][y]);
}
}