JSON structure for two JSON objects before parsing? - javascript

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

Related

Json array issue on binding to bootstrap datatable

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

How to Get key value from parseJson()

I have a case that is how to find the value of a key that is in sekrip as follows:
JSON.parse({
"data": [
{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}
]
});
The above data was obtained from:
<script type='text/javascript' src='http://domain.com/target.php'></script>
I want to get the value of the key "id_user", anyone can help me?
Thanks before.
Several issues here. Firstly, the method you're looking for is JSON.parse(), not parseJSON. Secondly, what you're providing to that function is already an object, not a JSON string, therefore it doesn't need to be deserialised as you can access it as you would any normal object:
var obj = {
"data": [{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}]
}
console.log(obj.data[0].id_user);
First its JSON.parse. Second it needs to be a JSON string.
Fiddle: http://jsfiddle.net/5m5qs1x4/
var jsonData = JSON.parse('{"data": [{"id_user": "351023","name": "","age": "29","link": "http://domain.com"}]}');
document.getElementById('test').textContent = jsonData.data[0].id_user;
You need to parse JSON string and than, access to keys/index
var data = JSON.parse("{\"data\": [{ \"id_user\": \"351023\",\"name\": \"\",\"age\": \"29\",\"link\": \"http://domain.com\"}]}");
document.write(data["data"][0]["id_user"]);

Unable to read json data to draw a graph

I am new to jQuery and json. Trying to draw a graph with reference to the demo from
http://www.highcharts.com/stock/demo/
This graph uses data from a json file
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
this file directly started with data. But the json file that I want to use looks something like this
{"name": {
"text1": "on",
"data": {
[1147651200000,67.79],
[1147737600000,64.98],
[1147824000000,65.26],
[1147910400000,63.18],
[1147996800000,64.51],
[1148256000000,63.38],
[1148342400000,63.15],
[1148428800000,63.34],
[1148515200000,64.33],
[1148601600000,63.55],
[1148947200000,61.22],
[1149033600000,59.77],
}
}}
could someone help me with this please
Your json is invalid.
If your data property is an array, so you should use [] to denote the array.
I'm assuming that array is an array of arrays, so inside [], it should have multiple []s.
Like:
[[x1,y1],[x2,y2]...]
Try formatting your code sample as follows...
{
"name": {
"text1": "on",
"data": [
[
1147651200000,
67.79
],
[
1147651200000,
67.79
]
]
}
}
Use something like http://jsonlint.com/ to check your json's validity.

Traversing a JSON object

The data which I fetch from PHP page is like:
[{
"id": "1",
"name": null,
"startdate": "2012-07-20",
"starttime": "09:53:02",
"enddate": "2012-07-20",
"endtime": "09:54:10",
"duration": "01:00:00",
"feedbacks": [{
"id": "1",
"type": "1",
"content": "cont"
}],
"conditions": [{
"id": "1",
"dev_id": "1",
"mod_id": "2",
"sub_id": "3",
"to_be_compared_value": "1",
"comparison_type": "1"
}],
"actions": [{
"id": "1",
"dev_id": "1",
"mod_id": "1",
"sub_id": "1",
"target_action": "1"
}]
}]
Which way is easy, efficent and elegant to traverse this object? I used this two until this time. Can you tell me which one must be my choice, or can you give me an alternative? And why? I have a running version of my application and I'm reviewing now my own code, and I want to take some advices from you all.
Thanks in advance,
Methods I use before:
$.map
for(var i in obj)
One more to go, I will create a table from this data.
I would use jQuery's each() (or map() if I wanted to change the data)
I should add that you should also create a function which returns an object (possibly even with some utility methods), since your data isn't very JS-friendly right now. Those dates and times, those ID's as strings.
Example:
function cleanMyObject(object){
var cleanFeedbacks = function(feedbacks){
/* ... */
return feedback;
};
object.start = /* transform date and time strings to datetime object ...*/
object.end = /*...*/
/*...*/
$.map(object.feedbacks,cleanFeedbacks);
/* cleanup the remaining objects... */
return object;
}
$.map(receivedData, cleanMyObject);
// cleanMyObject() returns the modified object so $.map will clean everything in your array.
I prefer to use http://underscorejs.org/ for things like this. It has a lot of useful functions for objects, collections etc.
If the data you are recieving doesn't change, just parse the object and use the keys you need.
All browsers I'm aware of have a function called JSON.parse to convert a JSON string into a JS object.
What I'm trying to say is: Don't be lazy, you aren't gaining any benefits from writing a "general" function if your object will always provide the same data, and there is little to no chance you can use that function again with a different object.
var myobj= JSON.parse(phpJSONstring);
var feedbacks= myobj["feedbacks"];
//do something with feedbacks
var conditions= myobj["conditions"];
//do something with conditions
etc
You can transform the json string in a javascript object, and then access the object like this:
var obj = jQuery.parseJSON(jsonString);
alert('Id='+obj.id);
var feedbackList = obj.feedbacks;
for (var i=0; i<feedbackList.length; i++) {
...
}
Reference to jQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/

Json returns every character as a separate object?

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

Categories

Resources