How to extract values from json using JSON.parse - javascript

I am having the following code:
data = JSON.stringify({
"result": [
{
"username": "username should not empty"
},
{
"password": "password should not empty"
}
],
"validate_flag": 1
})
data = JSON.parse(data);
$.each(data,function(index,value){
console.log(index);
console.log(value);
});
console.log(data);
Here I can extract the second key "validate_flag" directly using $.each. But when I tried to extract "result" I got two objects. Now,how can I effectively use $.each() to extract the following json regardless of multi-dimensional or single-dimensional. Also how can I access object in the key value "username" and "password"? Here is the link for fiddle I tried?

Try this: http://jsfiddle.net/zds6M/3/
var echoOut = function(data){
$.each(data,function(i,v){
if(typeof v == 'object'){
console.log('In: ' + i);
echoOut(v);
}else{
console.log(i + ': ' + v);
}
});
};
data = JSON.parse(data);
echoOut(data);

properties of an object in javascript can be accessed via
for in loop
for (var x in yourobject)
{
// key is x
// value is object[x]
}
if you already know the property name
than use can use yourobject["propertyname"] or yourobject.propertyname

Related

Json key and value in javascript

My Link json test file is the following:
[{"google" : "https://google.com"},{"bing" : "https://bing.com"}]
The javascript requesting the value, using axios:
var Links = './Links'
axios.get(Links)
.then(function(response){
console.log(response.data["google"]);
try {
var Test12 = JSON.stringify(response.data["google"]);
} catch (err) {
var Test12 = 'nothing'
}
The result is undefined.
My goal is to return the value of the input "google" or any input from the JSON and store it in the var as a string.
Since its an array of objects so you should access the values like,
response.data[0].google
OR
response.data[0]["google"]
Your data file is a list with two objects in it.
To access the google item you should access the list element.
var Test12 = JSON.stringify(response.data[0]["google"]);
Although I would change the json file to:
{"google" : "https://google.com", "bing" : "https://bing.com"}
Maybe like this:
var data=[{"google" : "https://google.com"},{"bing" : "https://bing.com"}];
data.forEach(function(el, index) {
Object.keys(el).forEach(function(val) {
console.log(val + " => " + el[val]);
});
});

parse values from javascript object

I see there is a problem to get a String name from JSON object's name.
I need to parse this kind on JSON response from server.
var response = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1
}
}
It is not an Array, but the object with inner objects.
i need to parse an inner ojects name and add additional values to each object.
i want be able to do something like this:
for(var i =0; i < response.length; i++){
response[i].username = parseUsernameFromString(response[i]);
response[i].service = parseServiceFromString(response[i]);
response[i].id = parseIdString(response[i]);
}
(and also state for each task)
So the question is:
What is the best way to make it?
UPDATE
this is exactly what i have for now:
for(var key in response){
if(stringContains(response[key], "Gmail")) { response[key].service = "Gmail";}
console.log("task name: "+ response[key].service);
}
function stringContains(originalString, searchString){
if(originalString.indexOf(searchString) > -1){
return true
}
else return false;
}
For walking through Objects, you need to use for ... in loop.
The real problem is: There's a , missing in your code. See the fixed working snippet:
Snippet
var response_Parsed = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1,
service: 'Gmail',
username: 'hopaop',
id: 'sjIpW'
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1,
service: 'Gmail',
username: 'hopaop',
id: '4y4yu'
}
};
for (id in response_Parsed) {
console.log("----");
if (id.indexOf("Gmail") > -1) {
console.log("We have Gmail: " + id);
console.log("UniqueName: " + id.replace("hopaopGmail", ""));
console.log("Username: " + response_Parsed[id].username);
console.log("Email Count: " + response_Parsed[id][id.replace("hopaop", "") + "_totalEmails_count"]);
}
else
console.log("We don't have Gmail: " + id);
}
And also the right way to enumerate the through the keys of the objects, is by using Object.keys.
If the response is a String like you wrote, you should first parse the JSON-String into an Object (if you're using a library like jQuery, it's probably already a JSON, as this conversion is done by jQuery automatically):
var obj = JSON.parse(responseString);
Afterwards you may iterate through it like posted above:
for (var key in obj) {
console.log("key", key, "value", obj[key]);
}

How read of Object.keys() value JSON?

How read of Object.keys() value JSON ?
I trying read value key name, but give error:
Keys dynamic
{
"marka1": {
"name": "Mika",
},
"beti1": {
"name": "Yii",
}
}
var ojson = JSON.parse(objectJson);
var keys = Object.keys(ojson); //read good key
console.log("test - " + ojson.keys[0].name); //give error
Change it to console.log("test - " + ojson[ keys[0] ].name); because keys[0] is just a string.

Parsing JSON to something usable

I know there are 1 million and 1 questions on this, but I cannot seem to find an answer.
I am receiving data via PHP as such
echo json_encode($result);
From a typical MYSQL query.
I get the result back like this in the console.
[{"id" : "1", "name" : "bob"}]
I am trying to use $.each to iterate through this so I can process my results but I only get errors, undefineds or 0[object Object].. things like that.
My goal is to append each value to a input box (retrieving data from a table to put into an edit box).
$.post('getstuff.php', { id : id } function(data){
$.each(data), function(k,v){
$('input[name= k ]').val(v);
});
});
As you can see i was hoping it was as simple as a key=>value pair but apparantly not. I have tried parsing, stringifiying.. really I am lost at this point. I also cannot tell $.post that I am using JSON because I am using a more arbitrary function, but am just posting that as my example.
Edit
var retrievedData = JSON.parse(data);
$.each(retrievedData, function(k,v){
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
});
In your second code sample, retrievedData is an array, which you iterate using jQuery $each...
$.each(retrievedData, function(k, v) {
OK so far. But then you try to iterate retrievedData again like an object, which it isn't. This is why you are getting undefined messages in the console
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
On the inner loop you should be iterating v not retrievedData. On each pass of $each v will be an object.Try this:
$.each(retrievedData, function(k,v){
for (var key in v) {
if (v.hasOwnProperty(key)) {
console.log("key: " + key);
console.log("value: " + v[key]);
}
}
});
You should do some type checking that v is an object first and catch any errors.
Use either :
$.ajax({
'dataType' : 'json'
});
Or
$.getJSON
Or if you want to use $.post, just do in your success function :
var good_data = JSON.parse(data);
$.each(good_data, function(k,v) {
$('input[name= k ]').val(v);
});
Answering your question based on your comments on other answer.
My assumption is you are getting data as JSON,if not you need to parse it,for that you can use JSON.parse(string).
Here I'm using Underscore.js
var data=[{"id" : "1", "name" : "bob"}]
$(data).each(function(ind,obj){
var keys=_.keys(obj);
$(keys).each(function(i,ke){
console.log(ke)
console.log(obj[ke]);
})
});
Here is JSFiddle of working code
First you need to define you're expecting JSON in your POST request - http://api.jquery.com/jQuery.post/
Then you need to iterate through the response.
$.post('getstuff.php', { id : id } function(data){
//Assuming you get your response as [{"id" : "1", "name" : "bob"}], this is an array
//you need to iterate through it and get the object and then access the attributes in there
$.each(data), function(item){
$('input[name=' + item.name + ']').val(item.id);
});
}, 'json');
EDIT
If you want to iterate over the properties of the objects returned, you need to put another loop inside the $.each
for (var property in item) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
More about it here - Iterate through object properties
EDIT 2
To address the solution you've posted. You've used the wrong variable names. Here's a working fiddle - http://jsfiddle.net/EYsA5/
var $log = $('#log');
var data = '[{"id" : "1", "name" : "bob"}]'; //because we're parsing it in the next step
var retrievedData = JSON.parse(data);
for (var parentProp in retrievedData) { //this gets us each object in the array passed to us
if (retrievedData.hasOwnProperty(parentProp)) {
var item = retrievedData[parentProp];
for (var property in item) { //this gives us each property in each object
if (item.hasOwnProperty(property)) {
console.log(item[property]);
$log.prepend("<br>");
$log.prepend("Property name is - " + property);
$log.prepend("<br>");
$log.prepend("Value of property is - " + item[property]);
//do stuff
}
}
}
};

How to write JSON with jQuery?

I have this currencies.json file:
{
"USD": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
},
"EUR": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
}
}
I need to parse it into "#content" using jQuery. Can someone help me with a code to do this? I think jSONP is needed because the feed is from another server.
Example for output needed:
<div class="currency">USD, 325.33, 344.55, 324.55, 354.55</div>
<div class="currency">EUR, 325.33, 344.55, 324.55, 354.55</div>
// you will get from server
var obj = $.parseJSON(data); // data contains the string
for (var key in obj) {
$('<div class="currency" />')
.html(key + ', ' + $.map(obj[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
HERE is the code.
$.parseJSON is used to parse the string into the object.
Then for each currency inside object use .map() to map the values.
Join the values into a string separated by ,, append into the div and a currency name.
Resulting div append to the body.
Update (see comments):
If you want to retrieve this data cross-domain use:
$.getJSON('www.domain.com/currencies.json?callback=?', function(data) {
for (var key in data) {
$('<div class="currency" />')
.html(key + ', ' + $.map(data[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
});
Something like this should help (the data parsed from your JSON above is held in the data variable):
var $body = $("body"),
key,
$div,
txt,
innerKey;
for (key in data) {
if (data.hasOwnProperty(key)) {
$div= $("<div></div").addClass("currency");
txt = [key, ", "];
for (innerKey in data[key]) {
if (data[key].hasOwnProperty(innerKey)) {
txt.push(data[key][innerKey]);
txt.push(", ");
}
}
// Remove the trailing comma
txt.pop();
// Set the HTML content of the div and then add to the body
$div.html(txt.join("")).appendTo($body);
}
}
Here's a working example jsFiddle.
well you can access things like:
data.USD.ValueUSD will get you 325.33 so you can do something liek this. pass your data object that you get from your ajax call in ur success func to call this function:
function populateContent(data){
var $currencyDiv = $('<div class="currency"></div>'),
$currencyDiv2 = $currencyDiv.clone();
$currencyDiv.html("USD, "+data.USD.ValueUSD + ", " + data.USD.ValueEUR + ", " + data.USD.PreviousValueUSD + ", " + data.USD.PreviousValueEUR);
//do the same for currencydiv2
//append your new content divs wherever you want
$('body').append($currencyDiv);
}
A more puristic approach that could also help you understand how to iterate through objects (and is browser native and therefore not relying on jQuery)
for(var data in #YOUR_JSON_DATA# ){ // iterate through the JSON nodes
var tmp = data; // store the current node in temporary variable
for(var val in json[data]){ // iterate through the current nodes' children
tmp += ", " + json[data][val]; // this is how you access multidimensional objects. format your output as you like
}
alert(tmp); // see the output. here you could use jquery to write this into your page.
}

Categories