JSON.parse(). Accessing data and using it to populate dom - javascript

JSON.parse Syntax: JSON.parse(text[, reviver]) Parameters: text-The string to parse as JSON. reviver- Optional If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Return value The Object corresponding to the given JSON text.
I really don't understand this. I have a JSON file that I need to use the data within to populate the DOM but I don't understand JSON.parse. When I tried to use this I used
var myData = JSON.parse({ "site": { "id": "example", "name": "example1" }...etc});
then tried to access it using dot notation.
console.log(myData.site.id);
I don't know what I'm doing, I've now figured out 200+ ways not to do it

JSON.parse expects a JSON string as its parameter, but you are passing javascript object literal, which is an object already and does not need parsing.
Depending on your use case you can either add quotes to make the parameter string:
var myData = JSON.parse('{ "site": { "id": "example", "name": "example1" }}');
Or don't use JSON.parse at all and you can work with your object directly.
var myData = { "site": { "id": "example", "name": "example1" }};

Pass JSON string to JSON.parse(yourJSONString) Then you can get values by call headers as follows.
var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
Then
myRst.site.id
var myRst = JSON.parse('{ "site": { "id": "example", "name": "example1" }}')
console.log(myRst.site.id)

Related

How do i access my json array with key named "data" in javascript?

I have json response returned from a rest api as below
{
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
I use jsonparse to convert it into object in javascript as below
var obj = JSON.parse(e.data)
When i access obj.extra.message it prints "Hello".
But when i try to access obj.data[0] , i get [object][Object] ,
seems like its taking "data" as a keyword?
How can i overcome this?
Note that you have your object inside an array.
Javascript doesn't show the whole object; you must use object's keys to access its data.
Obj.data[0] is the whole object.
It seems that your response is already JSON. So don't parse it again:
const data = {
"data":[
{
"id":"86",
"name":"Hello",
"last_name":"world"
}
],
"extra":{
"message":"Hello",
"additionalmessage":"world"
}
}
console.log(data["data"][0].name);
The parsing is working just fine; it's just that when you output the first element, you're just outputting the object, not one of its properties. The default toString on an object outputs [object Object]
You can try this:
var user = obj['data'][0];
console.log(user.name);
console.log(user.last_name);
Or try
JSON.stingify(obj.data[0])
here's how you can do it:
var obj = {
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
console.log(obj["data"][0]["id"]);

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 access js property

I've json in this format :
[
{
"_id": {
"$oid": "560c079e1691682b4ff327ad"
},
"year": "2015",
"month": "9",
"day": "30",
"time": "17:02:17",
"problemDesc": "test",
"resolution": "test",
"IM": "test"
}
]
I'm attempting to access the year using : console.log(json[0].year) but receiving undefined. How to access the year value from this json string ?
fiddle :
http://jsfiddle.net/b8dggkof/
In the JSFiddle the value inside json is a string and not a JavaScript Object, you have to parse the string before try to access the value:
var json = JSON.parse('{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}');
console.log(json[''][0].year);
After you parsed the string, you need to access the object with key an empty string:
json['']
The value associated to this key is an array and you need the first element, so:
json[''][0]
Now you can get the year:
json[''][0].year
You need to put in a key for the JSON and then access by the key the inner Object, after you parse it since it is a string enclosed in quotes '
var json = '{"key":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}'
console.log(JSON.parse(json)['key'][0].year);
you need to parse you json string to json object by using JSON.parse then use key name in you case which is ''(empty string)
var jsonStr = '{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}';
var parseJson = JSON.parse(jsonStr);
alert(parseJson[''][0].year)

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 structure for two JSON objects before parsing?

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

Categories

Resources