Get Data from JSON String - javascript

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]);
}
}

Related

how to fetch json data in scope variable angularjs

Here is my Json data
"data": {
"address": {
"postalCode": "112629",
"state": "DL",
"city": "new city",
"streetAddress": "my street"
},
"specialities": [
{
"_id": "577692f7",
"name": "Football",
"description": "game",
"__v": 0
}
]
}
$scope.test = data;
i am fetching data in html by
ng-repeat="mytest in test" than
mytest.address.city // this is working fine
mytest.specialities.name // not printing anything
i am facing the problem in accessing the specialities name i think that is because of specialities is a array but don't know how to get it.
You defined a specialities object with only one array inside
try
mytest.specialities[0].name
Update:
Also you may want to make sure that the array has at least one element, otherwise you mayget a TypeError: Cannot read property 'name' of undefined.
So the code sould look like this:
mytest.specialities.length > 0 ? mytest.specialities[0].name : '(some default value)';
Assuming there will be many specialities you should use ng-repeat to display them all.
<p ng-repeat="s in mytest.specialities"> {{s.name}} / {{s._id}} / {{s.description}} </p>
Yes mytest.specialities is array. JSON has two possible options [ ] - array, { } - object. In this situation we have array of objects - [ { /* object data */ } ] so to get object parameter first go to array element like this ( example getting first element on index 0 ):
mytest.specialities[0].name
second element:
mytest.specialities[1].name
example each:
<div ng-repeat="special in mytest.specialities">
<span>{{special.name}}</span>
</div>
of course before that set mytest to scope like:
$scope.mytest=mytest;//mytest is your data structure

jQuery: Get JSON error

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:
// data.json
{
"stuff": [
{
"userId": 1,
"date": "19 Oct 2014",
"content": "#New Hello on g.co/ABC",
"entities": {
"hashtags": ["#New"],
"urls": ["g.co/ABC"]
}
}
],
"user": {
"avatar": "/assets/avatar.jpg",
"name": "Daniel"
}
}
Now my jQuery code is:
$(document).ready(function(){
$.getJSON('data.json', function(data) {
//console.log(data);
$.each(data,function(i,item){
console.log(item.stuff.content); // I want to print 'content'
});
});
});
And all I get is an Uncaught error type:
What am I doing wrong? Thanks in advance
stuff is an array of object.
To access item of an array you have to access it via index
like this
console.log(data.stuff[0].content);
JSFIDDLE
May be you are iterating an object instead of array of object
If data is an object then try like this
$.each(data.stuff,function(i,item){
console.log(item.content);
});
JSFIDDLE
This should work:
$.getJSON('data.json', function(data) {
console.log(data['stuff'][0]['content']);
}
It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.
You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.
$(document).ready(function(){
$.getJSON('data.json', function(data) {
console.log(data.stuff[0].content);
//or loop through like
//$.each(data.stuff,function(i,item){
// console.log(item.content);
//});
});
});

JSON Stringify Ouput to Multiple Lines

I'm writing a simple JS app that takes in a JSON file, displays the information to the user and allows them to modify it, and then allows them to re-export the JSON. However, the JSON that is being brought in is multi-line; each key/value is on its own line. When I use .stringify to output the JSON, it all appears on one line. Is there any way for the stringify method to separate the lines?
JSON Structure:
{"Title":
{"lvlOne":[
{"key":"val"},
{"key":"val"},
{"key":"val"}
],
"lvl2":[
{"key":"val"},
{"key":"val"},
{"key":"val"}
]}
}
But when I output, it all shows:
{"Title":{"lvlOne":[{"key":"val"},{"key":"val"},{"key":"val"}],"lvl2":[{"key":"val"{"key":"val"},{"key":"val"}]}}
You can use the space parameter of the stringify method. From the official page, here is the relevant excerpt:
JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'
you can also use.
var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, '\t');
console.log(json);
Or even better, the count of spaces in the indentation:
var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, 2);
None of the above worked for me the only thing that worked for me was
await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;

How to get data from json in order to save them in database?

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

How do I access JSON elements through javascript?

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'].

Categories

Resources