Display json object in angularjs codemirror - javascript

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

Related

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" });

wierd json error in jQuery

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.

AngularJS - Pushing JSON data (structure correct, but something missing)

I'm completely new to AngularJS and I'm converting a small app at the moment, although there's one thing tripping me up.
My goal is to add a module to the dashboard and everything works correctly if I hardcode the JSON data, although, it seems to be having issues when using a variable.
My service:
var pushData = angular.toJson({"modID": "mod_rText_01", "sequence": 1, "group": 1, "dashboard": 1, "type": "text", "content": ["17%", "operating capacity"]});
console.log(' :: Module data pushed: ' + pushData);
$rootScope.$broadcast('locations', pushData); // broadcast to controller
My controller:
// listen for service location updates
$scope.$on('locations', function(event, pushData) {
console.log(' :: Module data received: ' + pushData);
$scope.locations.push(pushData);
});
Console logs:
:: Module data pushed: {"modID":"mod_rText_01","sequence":1,"group":1,"dashboard":1,"type":"text","content":["17%","operating capacity"]}
:: Module data received: {"modID":"mod_rText_01","sequence":1,"group":1,"dashboard":1,"type":"text","content":["17%","operating capacity"]}
As mentioned, if I change the controller line to be: $scope.locations.push({"modID":"mod_rText_01","sequence":1,"group":1,"dashboard":1,"type":"text","content":["17%","operating capacity"]});
It works correctly. I feel I'm missing something! Although, according to the console.log, the variable 'pushData' is correct, but nothing happens.
Any help will be greatly appreciated!
The problem is that you transform your object to JSON.
What you are doing here is you actually send a STRING, not an object.
angular.toJson({"modID": "mod_rText_01", "sequence": 1, "group": 1, "dashboard": 1, "type": "text", "content": ["17%", "operating capacity"]});
This string is being published in event and picked up in controller. So in below code, instead of an object, you are really adding a string to an array:
$scope.locations.push(pushData);
Solution: just publish regular JavaScript object instead of string and it should work as expected. $broadcast() and $on() are capable to work with real objects as well.
var dataObj = {"modID": "mod_rText_01", "sequence": 1, "group": 1, "dashboard": 1, "type": "text", "content": ["17%", "operating capacity"]};
$rootScope.$broadcast('locations', dataObj);

JSON validation

I'm trying to work with json-framework on iPhone to parse a json string.
When I'm calling this method:
NSDictionary *dictionary = [jsonString JSONValue];
I'm getting the error:
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key:
Options\" UserInfo=0x4b5f390 {NSUnderlyingError=0x4b5f320 \"Expected value while
parsing array\", NSLocalizedDescription=Object value expected for key: Options}"
According to this json validator [1]: http://www.jsonlint.com// my json is not valid. But is that so??
My json string looks like this:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary",
}
}
* Edited Json: (still brings up an error)
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary"
}
]
}
Your JSON is not valid.
It's because you can't create object instances within JSON. It's not a valid value.
new Date(2011, 0, 7, 12, 30, 0)
And you missed the closing array bracket. Everything else is ok.
remove the comma after ...Binary"
add a ] between the two } }.
Date cant be used like this, see How do I format a Microsoft JSON date? and http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb
This is valid:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": "new Date(2011,0,7,12,30,0)",
"Type": "Binary"
}
]
}
You can't instantiate Date objects (or any objects) in a JSON string.
You need to have whoever's responsible for the code that emits this JSON change it to emit valid JSON. They're putting out something now that can't work with any JSON parser. Maybe they have a customized JSON consumer that can handle such things, but this isn't standard JSON.
If I were you, I'd have them put the string of the current date into that field (so: "2011-07-01 12:30:00") and then parse that in your obj-cusing NSDateFormatter.
If whatever puts out that JSON isn't something you can change, you can always modify it locally before feeding it to the JSON library. It's just a string, nothing magical.

Categories