json comes in as object not string - javascript

Json is sitting on my localhost as: /data/:
{
"children": [
{
"name": "analytics",
"size": "1243"
},
{
"name": "math",
"size": "4343"
},
{
"name": "algebra",
"size": "1936"
},
{
"name": "calc",
"size": "3936"
},
{
"name": "geom",
"size": "2136"
},
{
"name": "Quant",
"size": "4136"
}
]
}
Here is how I am trying to access the json:
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,name){
alert(json.children);
});
});
}, 3000);
The data comes in just fine. That is, when I run console.log(json) I can see the above json name/value txt pairs in firebug. However, before each name value pair I see the word Object. So for example instead of my log showing { name="analytics", size="1243"},.. it actually shows: [Object { name="analytics", size="1243"},... And that too is what my alert shows: [object Object] instead of name="analytics", size="1243".
Why is this and is there a way to get my json name/value pairs in text so that I can store as a javascript String?
Many thanks in advance.

jQuery does automatically decode the response when using jQuery.getJSON or specifying the response as JSON. If you want the plain response, use jQuery.ajax instead.

The O in JSON stands for "object." It's a way of serializing a JavaScript object to a string (and back). You seem to be relying on the conversion on one hand (referencing children) but not want to have the conversion done on the other hand. If you really want children to be a collection of strings in the format you describe, you should store it that way. If you really do want the object notation (and conversion to objects in the client), then you can simply use the properties of the object.
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,item){
alert("name = " + item.name + ", size = " + item.size);
});
});
}, 3000);

Everything you've stated is normal behavior for both firebug and alert. You can't alert an object.
Here's example of how to loop the response within your $.get callback
http://jsfiddle.net/Y3N4S/
$.each(json.children, function(i, item){
$('body').append('<p>Name: '+item.name+' , Size: '+item.size+'</p>')
})

Well, working with Objects is the intend of "Javascript Object Notation".
Actually, your json is an Array of Objects.
{
"children": [ // <-- Array
{...},// <- Object
{...} // <- Object
]
}
You can access your key-value pairs this way: children[0].name
for (var i=0;i< children.length; ++){
console.log( children[i].name);
console.log( children[i].size);
}

Related

JSON object array return undefined

I have below scripts on Google Apps Script which will take in an JSON event.
I want the data in element "events", but it always return "Undefined" to me.
I'm guessing maybe it's because events is a JSON array and I can't directly use it in JS?
Here is my code:
function doPost(e) {
var msg = JSON.parse(JSON.stringify(e.postData.contents));
console.log(msg);
//log succesfully
console.log(msg.events);
//"Undefined"
}
If I try to log the elements in the events instead of the array events itself:
console.log(msg.events[0].replyToken);
//"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"
The result of msg will is in below:
{
"destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
"events": [
{
"type": "message",
"message": {
"type": "text",
"id": "*********",
"text": "Hi"
},
"timestamp": 1642616050062,
"source": {
"type": "group",
"groupId": "***********",
"userId": "*************"
},
"replyToken": "************",
"mode": "active"
}
]
}
I've seen several similar problems for array in JS.
I tried them but all of them didn't work, please help me.
I guess the result your getting from your API as e.postData.contents is a JSON string.
In this case something like this:
var msg = JSON.parse(JSON.stringify(e.postData.contents));
would first try to turn something into a JSON string (JSON.stringify) and then converting it into a JavaScript object by JSON.parse. In other words the JSON.stringify is useless.
Try this instead:
var msg = JSON.parse(e.postData.contents);
If the value from "e.postData.contents" is already a string, you don't have to do JSON.stringify.
If you do JSON.parse(JSON.stringify(any string) it results in adding backslash" to the values. For example
let str = '{name: "John"}';
let myJSON = JSON.stringify(str);
myJSON = "{name: "John"}"
So, please make sure "e.postData.contents" is not a string.

How to parse nested JSON data using Javascript efficiently?

I have nested JSON data which I am trying to parse using Javascript:
[
{
"fullUrl": "https://replacedURL.org/v/r4/fhir/MedicationRequest/83b6c511-8b78-4fe2-b484-346ddee61933",
"resource": {
"resourceType": "MedicationRequest",
"id": "83b6c511-8b78-4fe2-b484-346ddee61933",
"meta": {
"versionId": "4",
"lastUpdated": "2021-04-06T03:14:44.834-04:00",
"tag": [
{
"system": "https://smarthealthit.org/tags",
"code": "synthea-5-2019"
}
]
},
"status": "active",
"intent": "order",
"medicationCodeableConcept": {
"coding": [
{
"system": "http://www.nlm.nih.gov/research/umls/rxnorm",
"code": "316049",
"display": "Hydrochlorothiazide 25 MG"
}
],
"text": "Hydrochlorothiazide 25 MG"
},
"subject": {
"reference": "Patient/2cda5aad-e409-4070-9a15-e1c35c46ed5a"
},
How do I parse and print the names all of the medications into a div element with id="meds" under the JSON key "text"? What I am trying which is incomplete:
for (var i = 0; i < prop.length; i++) {
if(typeof obj[prop[i]] == 'undefined')
return defval;
obj = obj[prop[i]];
document.getElementById("meds").innerText = obj ++ ;
}
Not entirely sure what do to here. Help please?
Steps to populate the DIV element with a list of medications include
Obtain the JSON text which encodes the data object.
Parse the JSON (text) to create a JavaScript Object value
Use the object obtained to list medications in a DIV element.
Implementing step 1 depends on the choice of communication API used on the frontend (e.g. fetch, axios or jQuery) or if the JSON string is hardcoded in a script element inserted into page HTML when serving the page.
Step 2 may be included in step 1 by some APIs automatically, based on the mime type of response content, or by executing some kind of json method on the response object. If the front end gets the JSON as a text string it can call JSON.parse to convert the text into an object.
Step 3 doesn't appear to need parsing - the text property is of a nested object in an array entry. Standard shortcut notation to access its value may suffice. For example:
// assume dataArray is the result of parsing the JSON text.
// assume "meds" is the id of a DIV element
function listMeds( dataArray) {
const div = document.getElementById("meds");
dataArray
.map(entry => entry.resource.medicationCodeableConcept.text)
.map( med=> {
const span = document.createElement("span");
span.textContent = med;
const br = document.createElement("br");
div.appendChild(span);
div.appendChild( br);
})
}

Getting values of json array in Mocha JS

I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)

JavaScript Json Array Parsing using Backbone

I have the following sample json:
{
"camp": [
{
"name": "Name",
"data": [
{
"date": "04/08/2014",
"value": 1000
},
{
"date": "05/08/2014",
"value": 1110
}
]
}
]
}
Here, I'm able to do: model.get("camp")[0], but when I try: model.get("camp")[0].get("data"), I get the following error:
undefined is not a function
Here model is the standard backbone model which extends Backbone.Model
I'm confused what I'm doing wrong !!
You only need to call the model.get() function once. After that, you can treat the returned object just like any other javascript-object. For example, you could do this to get one of the values deep inside the object:
model.get("camp")[0].data[0].value
To achieve what you are trying to get, do this:
model.get("camp")[0].data
If you want to acces a property of your json array, you should simply do like this:
var test = json.camp.name
This is how you get your value:
obj.camp[0].data[0]

Parsing a JSON object-within-an-object in javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

Categories

Resources