I have a json file:
{
"bible" : {
"#attributes" : {
"translation" : "ASV"
},
"testament" : [
{
"#attributes" : {
"name" : "Old"
},
"book" : [
{
"#attributes" : {
"name" : "Genesis"
}
},
{
"#attributes" : {
"name" : "Exodus"
}
},
{
"#attributes" : {
"name" : "Leviticus"
}
},
{
"#attributes" : {
"name" : "Numbers"
}
},
{
"#attributes" : {
"name" : "Deuteronomy"
}
},
{
"#attributes" : {
"name" : "Joshua"
}
},
{
"#attributes" : {
"name" : "Judges"
}
},
{
"#attributes" : {
"name" : "Ruth"
}
}
]
}
]
}
}
I am using code to read it:
$(document).ready(function(){
$.getJSON("asv/index.json", function(json) {
alert("JSON Data: " + json.bible.testament[1].name);
});
});
But this gives me undefined. Please let me know how to read book names. Also #attributes are what for?
Thanks
try this:
$.getJSON('asv/index.json',
function(json) {
$.each(json.bible.testament[0].book, // $.each() looping on each books
function(i, value) {
console.log(value['#attributes'].name); // here you get the name of books
});
json.bible.testament[1].name is undefined.
try json.bible.testament[1]['#attributes'].name
You have the wrong object path to your data. I recommend that you paste your json data into a viewer to make it easier to see what you need to get. Try http://jsonviewer.stack.hu/ for example.
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("asv/index.json", function(json) {
alert(json.bible.testament[0]['#attributes'].name);
alert(json.bible.testament[0].book[0]['#attributes'].name);
});
});
</script>
That works for me. Notice how you don't have any testament[1] index, only testament[0].
The #attributes part seems to be something the script that generates the JSON is creating, nothing you need to use JSON per say. I would remove it if I had access to the JSON-creating script, but perhaps it is used in some system that you do not see.
If you have a browser that supports console.log (Firefox for example) you can do a 'console.log(json)' and look at the structure.
You can access names like that:
json.bible.testament[0].book[0]['#attributes'].name
json.bible.testament[0].book[1]['#attributes'].name
...
Related
I am trying to "ADD" a new key "resource1" to my below JSON.
I tried jsonFile["entry"][2] = "resource1" . This worked.
Now i want to add an object with "resourceType", "code", "subject"...... like how it is displayed for "resource" in my json below. How do i achieve this???
Like this --> jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"} ?????
Need help here
jsonFile:
{
"resourceType" : "Bundle",
"type" : "transaction",
"entry" : [
{
"fullUrl": "urn:uuid:patient",
"resource" : {
"resourceType" : "Patient",
"name" : [
{
"given": ["Lola"],
"family": "Tes"
}
]
},
"request" : {
"method" : "POST",
"url" : "Patient"
}
},
{
"resource" : {
"resourceType" : "Observation",
"code" : {
"coding" : [
{
"system": "http://loinc.org",
"code": "15074-8",
"display": "Glucose [Moles/volume] in Blood"
}
]
},
"subject": {
"type" : "Patient",
"reference" : "urn:uuid:patient"
},
"valueQuantity": {
"value": "5",
"unit": "mmol/l",
"system": "http://unitofmeasure.org",
"code": "mmol/L"
}
},
"request" : {
"method" : "POST"
}
}
]
}
Looks like you are trying to add the property to non existing object.
From your example.
jsonFile["entry"][2] = "resource1"
this worked because you are adding this to existing property(i.e. jsonFile has entry object which is array. So, it's just simply pushing this to array.
But when you are trying this,
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
it's trying to add property to non extsting object(i.e. jsonFile has entry, but entry has only 0 and 1 position objects in array. So, this will throw error.
To add property at 2nd position, you need to initialise object at that position and then you can add property.
You can do it in following ways,
jsonFile["entry"][2] = {}
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
Or
jsonFile["entry"][2] = {"resource1":{"resourceType" : "Observation"}}
You can add property to object if and only if that object is exists.
I'm making chat app and storing the messages in firebase and this is my structure:
{
"1405093" : {
"172341" : {
"bot" : {
"msg" : [ {
"msg" : "hi",
"timestamp" : "12:09:02"
}, {
"msg" : "bye",
"timestamp" : "12:11:03"
} ]
},
"consultant" : {
"msg" : "Hi"
},
"resolved" : false,
"user" : {
"module" : "",
"msg" : [ {
"msg" : "hi",
"timestamp" : "12:09:01"
}, {
"msg" : "bye",
"timestamp" : "12:11:01"
} ]
}
},
"172351" : {
"bot" : {
"msg" : [ {
"msg" : "hi",
"timestamp" : "12:09:02"
}, {
"msg" : "bye",
"timestamp" : "12:11:03"
} ]
},
"consultant" : {
"msg" : "Hi"
},
"resolved" : true,
"user" : {
"module" : "",
"msg" : [ {
"msg" : "hi",
"timestamp" : "12:09:01"
}, {
"msg" : "bye",
"timestamp" : "12:11:01"
} ]
}
}}
And here is my code
if(method === "addUser&Bot")
{
umsg=data.umsg;
bmsg=data.bmsg;
ref.child(user+"/"+ticket_id).set({
"user":{
"msg":umsg,
"module":""
},
"bot":{
"msg":bmsg
},
"consultant":{
"msg":"Hi"
},
"resolved":false
});
data={"name":user,"id":ticket_id}
res.json(data);
}
As You can see I'm using set function and that's because of the field like 172341 which is actually a ticket_no which will always be unique and I don't want the randomly generated values created by firebase. So the problem is, this works great for the first time when the ticket_no is new but when again I'm sending a message the previous messages are overwritten. So how do I write a code that handles the new ticket_no and messages and also the messages that are sent afterwards.
If you want to only update the values that you're passing to the database, and leave anything you're not passing unmodified, use update(...) instead of set(...):
ref.child(user+"/"+ticket_id).update({
"user":{
"msg":umsg,
"module":""
},
"bot":{
"msg":bmsg
},
"consultant":{
"msg":"Hi"
},
"resolved":false
});
This will write only the user, bot, consultant, and resolved properties, and leave any other properties unmodified. But it will overwrite the complete value of the user, bot, consultant, and resolved properties. If you want to do a deep update, you can specify the precise path of what you want to update:
ref.child(user+"/"+ticket_id).update({
"user/msg": umsg,
"user/module": "",
"bot/msg": bmsg,
"consultant/msg": "Hi",
"resolved":false
});
This last statement will write/update only the precise paths indicated, and leave everything else unmodified.
I am trying to grab every project by the members within them -- I've created a sample datastructure though the actual structure is much larger (as in it would be difficult to restructure the database).
Here is my query:
var ref = new Firebase(FBURL + '/chat/meta/project');
var email = 'kerry#email.com';
ref
.orderByChild("email")
.equalTo(email)
.on("child_added", function(snapshot) {
console.log(snapshot.val());
}
);
It is important to note that if I remove the .equalTo(email) that it returns all of the "projects", when it should only return 2 of them.
Here is the data in Firebase:
{
"chat" : {
"meta" : {
"project" : {
"-KAgjWOxjk80HIbNr68M" : {
"name" : "Gman Branding",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:33:25.170Z",
"member" : {
"-KAgkD-2GVESwNwKP3fA" : {
"email" : "abc#gman.com"
},
"-KAgkP3M4nug9Bjn-vY6" : {
"email" : "def#gman.com"
},
"-KAgkP3OF0sUgc9x9p37" : {
"email" : "ghi#gman.com"
},
"-KAgkaMyEOiXft6o-HbO" : {
"email" : "kerry#email.com"
}
}
},
"-KAgl9xlPDU5T4072FgE" : {
"-KAglqH9pxkhgC84_kAl" : {
"name" : "YuDog",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:41:31.172Z"
},
"name" : "billing test 1",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-02-25T23:18:55.626Z",
"dateNotifyUnread" : "2016-01-25T23:23:55.626Z",
"member" : {
"-KAglNsswyk66qUZNrTU" : {
"email" : "kerry#email.com"
}
}
},
"-KAgltmLk2oOYhEDfwRL" : {
"-KAgm1Jt5q53gzLm1GIh" : {
"name" : "YuDog",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:41:31.172Z"
},
"name" : "YuDog",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:41:31.172Z",
"member" : {
"-KAgm1Jvss9AMZa1qDb7" : {
"email" : "joe#yudog.com"
}
}
},
"-KAgluTcE_2dv00XDm1L" : {
"-KAgm6ENmkpDiDG2lqZ4" : {
"name" : "YuDog Landing Page",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:41:31.172Z"
},
"-KAgmBptbeInutRzNinm" : {
"name" : "YuDog Landing Page",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:41:31.172Z"
},
"name" : "YuDog Landing Page",
"url" : "http://localhost:3000/project/abc123fasd123cc/...",
"date" : "2015-10-10T21:41:31.172Z",
"member" : {
"-KAgm6EQcvQg3oP-OnIF" : {
"email" : "joe#yudog.com"
},
"-KAgmBpwoxPYGXS9fLZ9" : {
"email" : "joe#yudog.com"
}
}
}
}
}
}
}
I've looked at 8-10 other links on SO but haven't found any that solve this issue.
The solution is to create a data structure that matches your needs. In this case, you want to look up the projects for a user based on their email address. So we'll add a node that contains this mapping:
"projects_by_email": {
"kerry#email,com": {
"-KAgjWOxjk80HIbNr68M": true,
"-KAgl9xlPDU5T4072FgE": true
},
"abc#gman,com": {
"-KAgjWOxjk80HIbNr68M": true
}
...
}
This is called denormalizing your data, although I often think of them as inverted indexes. I would probably keep the projects by uid, but the structure would be the same.
With a structure like this, you can get the list of projects for an email with a simple direct look up:
var ref = new Firebase(FBURL);
var email = 'kerry#email.com';
ref.child('projects_by_email')
.child(email)
.on("child_added", function(snapshot) {
console.log(snapshot.key());
}
);
Or if you then also want to "join" the projects themselves:
var ref = new Firebase(FBURL);
var email = 'kerry#email.com';
ref.child('projects_by_email')
.child(email)
.on("child_added", function(snapshot) {
ref.child('project').child(snapshot.key()).once('value', function(projectSnapshot) {
console.log(projectSnapshot.val());
});
}
);
This type of denormalizing is a normal part of NoSQL data modeling. The duplication may feel wasteful, but it is part of why NoSQL solution scale so well: none of the code above asks the database to consider all projects/all users. It's all directly accessing the correct nodes, which scales really well. So we're sacrificing storage space to gain improved performance/scalability; a typical space vs time trade-off.
I'm implementing an asynchronous webpage in Grails where I make a call to a controller and render the response as a D3.js network. I stored the object into a global variable for further use. The function worked fine when data is returned. However when I tried to use the object later I found some fields became undefined.
var similar;
function asynchroNetwork() {
var jsonData = $.ajax({
url: "${createLink(controller:'environment', action:'asynchro')}",
dataType: "json",
async: true
}).done(function(jsonData) {
console.log(jsonData);
//console.log(jsonText);
document.getElementById("result").innerHTML="Done";
console.log(jsonData.all);
//set global variable
similar=jsonData;
console.log("The object got");
console.log(similar);
draw();
});;
}
function draw(){
console.log(similar);
//draw the network based on object
}
The controller returns the following JSON:
{
"\u521B\u4E1A" : {
"nodes" : [{
"group" : 1,
"name" : "\u6c88\u9633\u8f9b\u98962\u4e16"
}
],
"links" : []
},
"all" : {
"nodes" : [{
"group" : 1,
"name" : "qwe25322570"
}, {
"group" : 1,
"name" : "\u660e\u5fb7\u7b03\u884c"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u53ef\u4e50"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u5f6d\u79c0\u8363"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u738b\u632f\u534e"
}, {
"group" : 1,
"name" : "\u6c88\u9633\u8f9b\u98962\u4e16"
}
],
"links" : [{
"value" : 1.0,
"target" : "\u6c88\u9633\u8f9b\u98962\u4e16",
"source" : "\u660e\u5fb7\u7b03\u884c"
}, {
"value" : 1.0,
"target" : "\u6c88\u9633\u8f9b\u98962\u4e16",
"source" : "qwe25322570"
}
]
}
}
In the draw() function it uses similar[all] to draw a graph. But in the links field I see the fields source and target are all undefined, while all fields in the nodes are all fine.
I don't think the encoding is the cause because nodes also contains UTF8 characters in the fields but none got missing. After the object is passed back from asychronous function the object similar is okay, but the next time draw() is called, I can see the field links go undefined.
Does anyone know what could be the cause of this problem? I guess it maybe related to nested fields.
Did you try passing your data as an argument to the draw function? If not, then:
In your ajax callback:
similar = jsonData;
draw(similar) //pass the json
draw function:
function draw(json) {
console.log(json);
}
Im trying to access some data and keep getting errors no matter what I try. Please help.
"rain":{"3h":13.625} is the part of the JSON file I am trying to access.
Here is what I have tried:
var currentRain = data.rain.3h; Which is most logical as it worked before but the number is what is giving the error.
var currentRain = data.rain["3h"];
var currentRain = data.rain[0]["3h"];
var currentRain = data.rain["3h"][0];
UPDATE:
This is the JSON payload:
{ "base" : "stations",
"clouds" : { "all" : 92 },
"cod" : 200,
"coord" : { "lat" : -33.850000000000001,
"lon" : 151.22
},
"dt" : 1429558616,
"id" : 6619279,
"main" : { "grnd_level" : 1024.97,
"humidity" : 100,
"pressure" : 1024.97,
"sea_level" : 1031.0999999999999,
"temp" : 288.77699999999999,
"temp_max" : 288.77699999999999,
"temp_min" : 288.77699999999999
},
"name" : "City of Sydney",
"rain" : { "3h" : 13.625 },
"sys" : { "country" : "AU",
"message" : 0.0101,
"sunrise" : 1429474880,
"sunset" : 1429514809
},
"weather" : [ { "description" : "heavy intensity rain",
"icon" : "10n",
"id" : 502,
"main" : "Rain"
} ],
"wind" : { "deg" : 157.5,
"speed" : 8.3200000000000003
}
}
You'll need to use ["bracket notation"] to access this, since "3h" begins with a number. As MDN explains:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
This is the correct JSON:
{
"rain": {
"3h": 13.625
}
}
First you need to parse it and transform into an object:
var jsonToObject = JSON.parse('{"rain":{"3h":13.625}}');
You can now access it like this:
jsonToObject.rain["3h"]
Just use data["rain"]. If you need to parse it first do JSON.parse(data) and then data["rain"].
OUTPUT
console.log(data["rain"]);
> { '3h': 13.625 }
...keep in mind that will return an Object.