I have extract a json format data from a table like this:
[ { id:"3",
"Date Extracted":"12/3",
Experiment:"normal"},
{ id:"2",
"Date Extracted":"12/3",
Experiment:"powder",
Notes:"" },
{ id:"1",
"Date Extracted":"12/3",
Experiment:"fine",
Notes:"" }
]
And I have used function like below to get only the attributes of each id like "12/3","normal", not include the name like "Date Extracted", Experiments.
Somehow this does not work.
but I have no idea how do it exactly in details.
var j = JSON.parse(data);
function(){
for(name in j.property.name)
console.log(j.property.value);
}
The extracted json data had some validation issues with the property names. You could verify your jsondata via jsonlint.com.
So the json data should likely be:
var jsonData ='[{ "id":"3", "Date Extracted":"12/3","Experiment":"normal"}, { "id":"2","Date Extracted":"12/3","Experiment":"powder","Notes":"" },{ "id":"1","Date Extracted":"12/3","Experiment":"fine","Notes":"" }]';
Function:
var json = $.parseJSON(jsonData);
$(json).each(function(i,val){
$.each(val,function(name,value){
console.log(name + " : " + value);
});
});
You can't use "for" like that.
var j = JSON.parse('[{ "id": "3", "Date Extracted": "12/3", "Experiment": "normal"}, { "id": "2", "Date Extracted": "12/3", "Experiment": "powder", "Notes": ""}, { "id": "1", "Date Extracted": "12/3", "Experiment": "fine", "Notes": ""}]');for(var i=0;i<j.length;i++){
var obj = j[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
console.log(attrValue);
}}
var data = [{
id: "3",
"Date Extracted": "12/3",
Experiment: "normal"
}, {
id: "2",
"Date Extracted": "12/3",
Experiment: "powder",
Notes: ""
}, {
id: "1",
"Date Extracted": "12/3",
Experiment: "fine",
Notes: ""
}];
for (var i = 0; i < data.length; i++) {
console.log("Date Extracted " + data[i]['Date Extracted'])//for index Date Extracted
console.log("Experiment " + data[i]['Experiment'])//for index Experiment
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can do using for loop like this
Related
I have below json array structure.. How can i get the key and value of each of the records json object?
{
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}
My expected output is to get the key and value... below as example:
<b>key</b> : cf_1, <b>value</b> : Clinic San
I have tried to loop in the records, but since i don't know the key, so i unable to get the value..
for (var z in records)
{
var value = records[z].cf_1;
alert(value);
}
//i don't know the key here.. i want to get the key and value
The full JSON structure is as below:
{
"forms": [{
"id": 1,
"records": [{
"cfsub_2": "1",
"cf_7": "1/3/2016",
"cf_1": "Clinic San",
"cf_2": "Fever",
"cf_3": "56.60",
"cfe_8": "dsf4334"
}, {
"cfsub_2": "2",
"cf_7": "3/3/2016",
"cf_1": "Clinic Raju",
"cf_2": "braces",
"cf_3": "183.50",
"cfe_8": "fresr4"
}]
}, {
"id": 7,
"records": [{
"cf_31": "27/3/2016",
"cf_32": "Singapore",
"cf_33": "dfd555",
"cfe_34": ""
}]
}, {
"id": 11,
"records": [{
"cfsub_10": "9",
"cf_9": "25/3/2016",
"cf_10": "256.50",
"cfe_11": "dfg44"
}]
}]
}
Hope this one is helpful for you.
$.each(value.forms, function(index,array){
$.each(array.records, function(ind,items){
$.each(items, function(indo,itemso){
alert( "Key -> "+indo + " : values -> " + itemso );
});
});
});
var getKeys = function (arr) {
var key, keys = [];
for (i = 0; i < arr.length; i++) {
for (key in arr[i]) {
if (arr[i].hasOwnProperty(key)) {
keys.push(key);
}
}
}
return keys;
};
Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};
The url has following json data:
[{ "topic": "cricket",
"value": "Player [ playerid=123, category=b, high=150, total=2300]",
"place": "xyz"},
{ "topic": "cricket",
"value": "Player [ playerid=456, category=c, high=60, total=300]",
"place": "abc"},
{ "topic": "cricket",
"value": "Player [ playerid=789, category=a, high=178, total=5300]",
"place": "bnm"}]
I tried online to check whether this is valid json or not through following link: http://jsonformatter.curiousconcept.com/ it says valid. if it is, how do I access each playerid ?
It is valid JSON, but the data about the player is embedded in a random string. You can do one of two things:
Update the service to send back a different, valid JS value, for example:
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
}
Parse the data in the value key yourself:
// Simple regex, not really "parsing"
var playerIdRE = /playerid=(\d+)/i;
var result = playerIdRE.exec(yourData[0].value);
// result[0] is the full match, while result[1] is the ID.
// Or the more complicated version that does full parsing
var format = /\s*(.*?)\s*\[\s*([^\]]+)\s*\]\s*/gi,
keyValuePair = /(\w+)=([^,\]]*),?\s*/gi
function parseComplexDataType(input) {
var result = format.exec(input),
typeName = result[1],
keyValues = result[2],
returnValue = {};
if (!typeName) return returnValue;
returnValue.typeName = typeName;
input.replace(keyValuePair, function(_, key, value) {
returnValue[key] = value;
});
return returnValue;
}
// Usage:
> parseComplexDataType("Player [ playerid=123, category=b, high=150, total=2300]")
Object {typeName: "Player", playerid: "123", category: "b", high: "150", total: "2300"}
For your purposes, it is not valid. Once the JSON is corrected, you simply need to loop through the array and read each value.
var jArray = [{
"topic": "cricket",
"value": {
"type": "Player",
"playerid": 123,
"category": "b",
"high": 150,
"total": 2300
},
"place": "xyz"
}, {
...
}]
To access the JSON data ...
for (var i=0,len=jArray.length; i<len; i++) {
console.log(jArray[i].topic, jArray[i].value.type);
}
Yes, it is. I check it via: http://jsonlint.com/
Extracting "playerid":
Initialise the string to JSONArray.
Iterate over each element in the above array.
Now, from each element extract "value".
Finally, from this string you can get "playerid" by using string methods (see the code below).
Below is the code in Java:
ArrayList<String> player_ids = new ArrayList<String>();
String s = "YOUR STRING";
JSONArray ja = new JSONArray(s);
for(int i =0; i<ja.length(); i++)
{
String value = ja.getJSONObject(i).getString("value");
int start = value.indexOf("=");
int end = value.indexOf(",");
String player_id = value.substring(start+1, end);
player_ids.add(player_id);
}
Hope it helps!!
I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable
Given json like this :
{ "rss": {
"page": 1,
"results": [{
"type": "text",
"$": 10
}],
"text": [{
"content": "Lorem ipsum dolor sit amet.",
"author": {
"name": "Cesar",
"email": "cesar#evoria.com"
},
},
{
"content": "Tema Tis rolod muspi merol.",
"author": {
"name": "Cleopatre",
"email": "cleopatre#pyramid.com"
},
}]
}
In javascript, I can retrieve value like this :
var json = JSON.parse(datajson);
$.each(json.text, function(key, val) {
// this one is ok
var content = val['content'];
// this one does not work
var authorname = val['author.name'];
});
Is this a way, given the attribute name in a string format, to retrieve the value of a complex object, for instance json.text[0].author.name?
EDIT
I would like to store the needed attributes in another object like :
[
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name"}
]
You can split your "index" by . and loop over "segments", descending through levels on each iteration.
var obj = {
author : {
name : "AuthorName"
}
}
function get_deep_index(obj, index) {
var segments = index.split('.')
var segments_len = segments.length
var currently_at = obj
for(var idx = 0; idx < segments_len; idx++) {
currently_at = currently_at[segments[idx]]
}
return currently_at
}
console.log(get_deep_index(obj, 'author.name'))
The following should fix the problem.
var authorname = val['author']['name'];
You can also store the object itself as:
var author = val['author'];
And then later on you can index the attributes from that.
console.log(author.name, author.email)
Yent give a good hint in the comments with the eval function. I resolve my needed with this kind of code:
var json = JSON.parse(myjsonasastring);
var descriptiontobeadded = [
{ dt: "Text content", dd: "content" },
{ dt: "Author name", dd: "author.name" }
];
$.each(descriptiontobeadded, function(key, val) {
var dt = '<dt>' + val.dt + '</dt>';
description.append(dt);
var dl = '<dd>' + eval('json.' + val.dd) + '</dd>';
description.append(dl);
});