wierd json error in jQuery - javascript

I have following json:
{
"responseHeader": {
"status": 0,
"QTime": 1
},
"spellcheck": {
"suggestions": [
"a",
{
"numFound": 4,
"startOffset": 0,
"endOffset": 1,
"suggestion": [
"api",
"and",
"as",
"an"
]
},
"collation",
"api"
]
}
}
I want to access the 'suggestion' array and for that I am using this in jQuery:
$.getJSON('http://localhost:8983/solr/suggest/?q=' + query + '&wt=json&json.wrf=?', {
})
.done(function(response){
// just for testing
alert(response.spellcheck.suggestions.suggestion); // error: response.spellcheck is not defined
});
The value of 'response.spellcheck' is shown undefined whereas 'response.responseHeader' shows [object Object] and also I can access elements under responseHeader. But I cannot figure out what's the issue with 'spellcheck'. Help!

suggestions.suggestions can't work. suggestions is an array. You need to index the array with the [] operator to get to a specific suggestion.
Specifically, based on the JSON you posted, you want suggestions[1].suggestion.

use console.log for printing the response then you can do accordingly

The correct spelling is response.spellcheck.suggestions (you have used suggesstions) and this is an array, so you can look at its context using the index... for example:
alert(response.spellcheck.suggestions.suggestion[0]); // "a"
So you need:
response.spellcheck.suggestions.suggestion[1].suggestion
Example on JS Fiddle.

Related

How to access the right json value that is located through an array?

I'm currently using the fixture file to make sure it will be easier to call the right value.
cy.fixture('latestLead.json').then(function (lead) {
this.lead = lead
})
My son file is the following:
{
"status": 0,
"result": {
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Lead",
"url": "/services/data/v51.0/sobjects/Lead/111111111"
},
"Id": "111111111",
"Name": "Andres Latest Test"
}
]
}
}
The way that I'm trying to get the right value is the following:
cy.get(".gLFyf").type(this.lead.result.records.Id)
I'm able to get totalSize or done from the result object, but I'm not able to get any other value higher than that object. How can I get the Id value from the records Array?
You can access an array item (in your case it's the object) using the index position (in your case it's zero)
cy.get(".gLFyf").type(this.lead.result.records[0].Id)
try this
cy.get(".gLFyf").type(this.lead.result.records[0].Id)

Display json object in angularjs codemirror

I have a json object and want to display it on codemirror using angularjs codemirror but it got an error saying ui-codemirror cannot use an object or an array as a model. Then I tried to convert the object into string using JSON.stringify, the string does not format nicely in codemirror. Anyone can help me to figure out how to make my code in formatted nicely in codemirror?
Thanks
ex:
//inside javascript
$scope.code = {
"name": "user1",
"id": "34",
"value": [3, 5, 4]
};
$scope.editorOptions = {
lineWrapping : true,
lineNumbers: true,
mode: 'application/json',
};
//inside html
<ui-codemirror ui-codemirror-opts="editorOptions" ng-model="code"></ui-codemirror>
It returns an error for this: ui-codemirror cannot use an object or an array as a model
if I change to JSON.stringify($scope.code), code mirror display like this:
{"name":"user1","id":"34","value":[3,5,4]}
However, I want it to display as this:
{
"name": "user1",
"id": "34",
"value": [3, 5, 4]
}
Any help?
Thanks
You can specify the indentation:
$scope.codeView = JSON.stringify($scope.code, null, 4);
Live example

Having trouble accessing variables of JSON response in JAvascript

I am calling an API using an AJAX call and then processing the response ready for output. THe only problem is, I cannot seem to access what looks like an array inside the response object and I can't for the life of me figure out why. It would seem just a basic thing to do but when I try and call the particular response value directly and log it in the console, it shows undefined.
Here is my response object:
{
format: "small",
_links: {
self: {
href: "http://www-*******.net/v1/trading/exchange"
}
},
_embedded: {
exchangeData: [
server: {
time: "10:01",
date: "08.12.2014"
},
expert: {
quantity: "48,069",
country: {
..................
Now, the variable I want to be accessing is the 'quantity' value of the 'expert' object. I thought this would be the way to get it:
response._embedded.exchangeData['expert'].quantity
IS this correct? It is not returning any value and I thought this is usually such a straightforward thing to do.
THanks
In JSON brackets [] are for arrays. For example, you could have ["a", "b", "c"], which you access with a numeric offset, such as response[1].
Curly braces {} are for objects (similar to hash tables in other languages), such as {"first": "a", "second": "b", "third": "c"}, which you access by referencing the property by name, such as response.first.
The notation is pretty simple, see the specification here.
In this case, you should fix the JSON source to read:
{
"_embedded": {
"exchangeData": {
"server": {
"time": "10:01",
"date": "08.12.2014"
},
"expert": {
"quantity": "48,069",
"country": {
Note that the character after exchangeData is now a curly brace, not a regular bracket. Then, you access it with:
response._embedded.exchangeData.expert.quantity

How to create an JSON array like this in javascript

What is the best way to create an array that looks like the following:
[
{
"id":"1",
"value": true
},
{
"id":"3",
"value": false
},
{
"id":"5",
"value": true
},
{
"id":"6",
"value": false
},
{
"id":"9",
"value": true
},
]
My code:
//add to array
thing = {
"id" : 1,
"value" : "true"
};
thingArray.push(thing);
It does not seem to be properly formatted when I put the output in a JSON validator.
As I commented further up, make sure you're actually serializing it to JSON at some point. In your code example you're simply working with a JavaScript object, which isn't the same thing as JSON. Here's an example:
// start with a regular JavaScript array
var array = [];
// push some regular JavaScript objects to it
array.push({
id: 1,
value: true
});
array.push({
id: 2,
value: false
});
// serialize your JavaScript array into actual JSON
var json = JSON.stringify(array);
// do whatever you want with it...
console.log(json);
Here's a JSBin example.
Your code is fine. Here's some more code to get you started:
var arr = [];
arr.push({"id": 1, "value": "true"});
arr.push({"id": 2, "value": "false"});
console.dir(arr);
http://jsfiddle.net/gg014w0h/
You can run that fiddle and then check your console output. You'll see the contents of the array pretty clearly.
JSON validators will not like the trailing comma of the array. There is a difference between console.log(array) and console.log(JSON.stringify(array)). You may want to use the latter.
Also note that booleans are allowed in JSON:
"value": "true",
"value": true
Those are both valid and they mean different things.

push syntax in Javascript for an array within an array

"elements": [
{
"values": [
{
"value": 70
}
],
"dot-style": {
"dot-size": 2,
"halo-size": 2,
"type": "solid-dot"
},
"on-show": {
"type": ""
},
"font-size": 15,
"loop": false,
"type": "line",
"tip": "#val#%"
}
]
In the above array example I need to add data to values array which is part of elements array dynamically. How do I do it using JavaScript push method?
As you will see, it's much easier to conceptualise your code if it is formatted well. Tools like jsBeautifier can help with this task.
First, it's clear that elements is part of a JS object. We'll call it foo, but you'll have to change this to the correct name in your code.
foo.elements[0].values.push({
value: 'some value'
});
This will add a new object to the values array.
elements[0].values.push({"value": new_value});
if the above is named var obj,
obj['elements'][0]['values'].push(someValue);
Presuming elements is part of an object called myObj for the example below, you could use either syntax.
myObj["elements"][0]["values"].push({ value: "my new value" });
or
myObj.elements[0].values.push({ value: "my new value" });

Categories