I am having a json object like the one below which I am reading from an xml file. I can see on the alert that the json obj is being displayed.
Now that I have the json object I am trying to bind against a Bootstrap datatable like in this example
How to load JSON data into Bootstrap table?
Whatever I tried the bootstrap table won't get populated. I think is because my json object contains the "book", which is the object name while the example from the link above has just a Json array. However I tried to do book.author and it still not working.
This is my plnk attempt, if anyone can have a look and tell what I am doing wrong would be great. https://plnkr.co/edit/h9islDjHyz6Sxkhl
{
"book": [
{
"author": "Gambardella, Matthew",
"title": "XML Developer's Guide",
"genre": "Computer",
"price": "44.95",
"publish_date": "2000-10-01",
"description": "An in-depth look at creating applications \n with XML.",
"id": "bk101"
},
{
"author": "Ralls, Kim",
"title": "Midnight Rain",
"genre": "Fantasy",
"price": "5.95",
"publish_date": "2000-12-16",
"description": "A former architect battles corporate zombies, \n an evil sorceress, and her own childhood to become queen \n of the world.",
"id": "bk102"
}
]
}
var $table = $('#table');
var mydata = "";
//read data from XML
$.get('hello.xml', function(xml) {
var json = $.xml2json(xml);
console.log(json);
// This part is for displaying the json result in this example
var jsonAsString = JSON.stringify(json, null, 2);
setJsonVal(jsonAsString);
});
//set mydata variablle with the json obj from XML
function setJsonVal(value){
mydata = value;
alert(value)
}
$(function () {
$('#table').bootstrapTable({
data: mydata
});
});
You need to use JSON.parse() to convert the value to json and then you can access the book by using .book.
function setJsonVal(value){
mydata = JSON.parse(value).book;
alert(value)
$('#table').bootstrapTable({
data: mydata
});
}
Related
Using Datatables with a .json source file, I am trying to manipulate the data before it shows in the table. I'm trying to simply remove spaces and replace with a dash in this example.
There are two ways I understand to do some data manipulation. One is columnDefs the other is using dataSrc and return the data. Both fail when i try to utilize .split or .replace or even .toLowerCase()...
For example, I have columnDefs added like so:
columnDefs: [
{
"render": function ( data, type, row ) {
console.log(data);
var cn = data.split(" ").join("-").toLowerCase();
return cn;
},
"targets": 1
}
],
The console shows:
Uncaught TypeError: data.split is not a function
How do we manipulate the data with replace or the like?
My data looks like:
{
"Licensee": "Whistles for Woods",
"Contact Name": "Bob",
"Street": "2230 Trail",
"Suite / PO Box": 0,
"City": "Alturas",
"ST": "CA",
"Zip Code": 997733,
"Telephone": 0,
"Email Address": "bobc#email.com",
"Website Address": "www.domain.com",
"Fax": "No fax",
"Products": "whistle with custom logo",
"Categories": "Miscellaneous"
},
As discussed in the comments
We just want to make sure that we are indeed manipulating strings and not any other data type. So in this case we would change the code to look something like this:
columnDefs: [
{
"render": function ( data, type, row ) {
if(typeof data === 'string'){
//only if string manipulate
data = data.split(" ").join("-").toLowerCase();
}
// OR data = data.toString(); whichever is more convenient!
return data;
},
"targets": 1
}
],
I have my html working with javascript, and the file manifest.json to be read.
Here is my json file's code:
{
"name": "Project",
"description": "A template project",
"icon": "img/icon.svg",
"version": "X.X.X.X",
"developer": {
"name": "Daniell Mesquita",
"url": "http://about.me/daniellmesquita"
},
"shop_id": "1",
"manifest_version": 1,
"default_language": "en"
}
I need read each object as text, parsing in javascript. Example:
<h1>+ name +</h1>
<h2>+ description +</h2>
<img src="+ icon +"/>
<p>+ version +</p>
Too, how can I read sub-objects of "developer" object?
EDIT: Validated json. Thanks to #ADreNaLiNe-DJ and Curious Concept's JSON Formater for helping validate.
You might do like the following. It will get your object key value pairs flattened even if you have nested objects in your data structure.
var data = {
"name": "Project",
"description": "A template project",
"icon": "img/icon.svg",
"version": "X.X.X.X",
"developer":
{
"name": "Daniell Mesquita",
"url": "http://about.me/daniellmesquita"
},
"shop_id": "1",
"manifest_version": "1",
"default_language": "en",
},
stack = [[],[]];
function getKeyValuePairs(obj,stack) {
Object.keys(obj).forEach( e => obj[e] instanceof Object ? getKeyValuePairs(obj[e], stack) : (stack[0].push(e), stack[1].push(obj[e])));
}
getKeyValuePairs(data, stack);
document.write("<pre>" + JSON.stringify(stack,null,2) + "</pre>");
If the json is in a String variable convert it to an object. Then you can access the single values:
var obj = JSON.parse(jsonString);
var name = obj.name;
var version = obj.version;
var developerName = obj.developer.name;
Well you can use
yourJsonVarName.developer.name
yourJsonVarName.developer.url
try this!
Added
If your external file is in your domain maybe you can use this to retrieve your data inside json file.
$.getJSON( "manifest.json", function( data ) {
var name = data.developer.name;
var url = data.developer.url;
});
Previously I was using a json file with the following format:
[{"lat":43.788458853157117,"lng":-79.282781549043008,"category":"volunteer","name":"Rita","url":"", "description":"xxx is a member of 13"},{"lat":43.7,"lng":-79.4,"category":"organization","name":"TCAN","url":"http://tcan.ca","description":"Lorem ipsum"}]
Now I am attempting to generate the json file from a Drupal site and am getting the following structure. How can I reference the lowest level fields. I have looked at examples using d3.net but have not found any that apply.
{
"organizations": [
{
"member": {
"field_category": "organization",
"body": "A network of organizations in Toronto devoted to climate change mitigation and adaptation.",
"URL": "xxx.ca",
"title": "Toronto Climate Action Network",
"field_lat": 43.7,
"field_long": -79.4
}
},
{
"member": {
"field_category": "abc",
"body": "xxx.",
"URL": "",
"title": "yyy",
"field_lat": 43.7,
"field_long": -79.28
}
}
]
}
Assuming that your data is stored in the variable data:
var bottom = data.organizations.map(function(d) { return d.member; });
I am new to JSON and I have a rather basic question....
Here is an example of JSON that is a response from a PHP page. My intention is to have two JSON objects, Photos, and Comments. Unfortunately, my JSON is flawed and it is not formatted properly. I do not know how to structure the JSON so that I can get both objects. What should this look like, if the JSON were correct for two objects? In other words, what do I need between Photos and Comments to indicate that these are two different objects?:
{"Photos": [ {"Filename": "5962230079803.jpg", "PhotoID": "39"}] "Comments": [ {"UserID": "100000660901552", "Comment": "Hello!"}]}
You didn't close your array. Try this:
{
"Photos": [
{
"Filename": "5962230079803.jpg",
"PhotoID": "39"
}
],
"Comments": [
{
"UserID": "100000660901552",
"Comment": "Hello!"
}
]
}
Use JSONLint to validate your JSON
Add a comma between each element:
{
"Photos": [{"Filename": "5962230079803.jpg", "PhotoID": "39"}],
"Comments": [{"UserID": "100000660901552", "Comment": "Hello!"}]
}
If you're defining and parsing this JSON result, and storing it in variable obj, access the properties using:
var obj = JSON.parse( response ); //response is the string containing JSON
var photos = obj.Photos; //Array of photo objects
var comments = obj.Comments;//Array of comment objects
I don't think there is one right answer, but this should do fine:
{
"Photos": [{
"Filename": "5962230079803.jpg",
"PhotoID": "39"}],
"Comments": [{
"UserID": "100000660901552",
"Comment": "Hello!"}]
}
Note the added comma. So your structure was almost there. Now, assuming you parsed it into a variable response, you could access the separate parts like so:
response['Photos'];
response['Comments'];
I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);