I'm new to AngularJS so my mistake might be anywhere in my code and I can't find it. I'm using $HTTP GET method to retrieve data that's located in some server /page. After retrieving that data (which is JSON) I want to play with that string to retrieve the data properly, like name: number: and so on. But the thing is once I put that data into $scope.listOfCompanyUsers I can't touch it. If I try to $scope.listOfCompanyUsers.slice(..) or if I try any other string function on that object my entire webpage crashes. I "alert()"'d the $scope.listOfCompanyUsers and the result is:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
What I wanted to do is remove the pre and br tags from that string so I have a pure JSON string that I could play with but again any function I try on $scope.listOfCompanyUsers crashes my site. What do I do? I tried var someOtherVariable = $scope.listOfCompanyUsers but that variable doesn't work later. I'm adding parts of my code because my mistake might be somewhere else.
Controller:
$http({
method: 'GET',
url: '/someURL'
}).then(function successCallback(response) {
$scope.listOfCompanyUsers = response.data;
},
function errorCallback(response) {
alert(response.status);
});
Later on the same controller:
.
.
$scope.someFunction = function () {
.
.
else {
alert("Maximum of 9 other passengers!");
alert($scope.listOfCompanyUsers);
// In this alert I could see the $scope.listOfCompanyUsers as mentioned above
}
};
My target right now is to have a var objectOfUsers = [{admin: true, id:123, username: "name", last_name: "test", name: "something"}, {next user.}, .] but because I can't touch the $scope.listOfCompanyUsers I'm stuck.
The problem is that the server is adding some extra tags to the response that shouldn't be in there:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
Edit your server-side code, to remove: <pre> and </pre><br>.
Then the call will work.
Is your response a string? If your response has HTML tags, then that is not valid JS object format. It looks like you have a Javascript array with one object, enclosed by some HTML tags.
Therefore you won't be able to access anything within this using the object reference notation (.) until you treat it like a string and use String.prototype.replace and replace the tags, and then do a JSON.parse on the remaining string to convert it into an object
Very strange server response, so possible solutions are:
Change server response to standard JSON without unwanted <pre>
If You can not change response remove not wanted part of response using regular expression in JS. Working example how do that:
var response='<pre>[{"admin": true, "id": 123, "username": "someName","last_name": "someLastName", "name": "John Doe"}]</pre><br>';
var goodResponse=response.match(/>([^<]*)</)[1];//remove not wanted signs
var parsedGoodResonse=JSON.parse(goodResponse);
console.log(parsedGoodResonse);//here we have parse js array
In parsedGoodResonse You have object which can be "touched" so exactly what You need.
The problem with the extra tags is not on your code, it's on the server-side. You should check the code on the server and find the reason for those extra tags. They can't be there because they are making the response an invalid JSON.
Related
So I made a post related to me wanting to have my JSON file look like this:
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
instead of this:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
people recommended me to use parse_st to make my JSON look like the first piece of code, however my question (the reason I made a new post was because they gave a great tip, but never responded to it unfortunately and I wasn't really sure if I could edit my post regarding to a whole new subject basically), is it possible to use this directly on variables? they gave me this piece of code:
const result = "language=nl_NL&getExerciseTitle=test";
const parsed = queryString.parse(result);
as you can see it directly takes the variable + the value given to it, but I was wondering: I will always insert new data etc, so how can I apply it so it will always target the variable that could possibly change (instead of litterly writing language=nl_NL for example) I came to notice that whenever I insert the piece data: {id: getUrlParameter('id') in my ajax call, it will make my JSON look like the second one (but I do get my ID send), but whenever I take that piece out of it it will show up like the first one but it won't increment any longer. the complete ajax call looks like this:
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {id: getUrlParameter('id'), formData: $('#my_form').serialize()},
dataType: 'json',
}).done(function (response) {
});
});
}
Cheers!
I have been traversing through Stackoverflow and everywhere else on the web to try and find a solution to my issue..
I am working in Javascript and attempting to POST a small section of JSON to an endpoint in the API i know is working (I have completes the GET and POST manually in Postman)
Here is my issue..
I want dont really want to do the "GET" in my programme I just want to either reference the file or even just store it in a little variable.
So for example I have in my code:
var OauthUpload = {
"objects": [
{
"name": "api",
"serviceID": 16,
"properties": {}
}
],
"version": "integration",
"environment": "redshift"
}
Then I am trying to reference this in the JS function:
function ApiPostOauth (port) {
$.post(OauthUpload, "http://docker.dc.test.com:" + getActualPort(port) + "/rest/v1/oauth/import", runner);
}
But I am having no joy! I have seen a few different silutions but none seem to fit for me.
Basically I want a way to just:
Reference my own JSON as a variable and then insert tht so my function "ApiPostOauth" has that inserted before it runs?
Thanks guys
Steve
I have put together an example for your use. When executing this code, the server will return the same object it is sent. So the 'OauthUpload` object is sent as the request body and the server returns the exact same object. Note: if you don't see output in the output panel when running the sample I will need to restart the server (leave a comment). This is here to demonstrate:
[EDIT] - after re-reading your question, it appears you would like to pass the 'OauthUpload` object into the function. I've updated the example.
You have a mistake in your call to jQuery post() method. As shown in the comments, the first two arguments are reversed in the call to post().
Since you didn't pick up on that, I decided to provide an example using your code. Since I don't have your server, I stood up a server for this example. So the URL and port will be different, but the AJAX call will be the same.
Please pay close attention to the OauthUpload object. Notice the property names are no longer surrounded by ". I removed these quotes because they seemed to be causing you confusion about JavaScript objects and JSON strings (there is no such thing as a JSON Object regardless of what you read on the web - JSON is a string format).
Next, look at the differences between the call made to $.post() in my example and your code. You will see the URL comes first in that call.
let url = "//SimpleCORSEnabledServer--randycasburn.repl.co/rest/v1/oauth/import";
let OauthUpload = {
objects: [{
name: "api",
serviceID: 16,
properties: {}
}],
version: "integration",
environment: "redshift"
}
ApiPostOauth(OauthUpload);
function ApiPostOauth(data) {
$.post(url, data, runner)
}
function runner(data) {
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
<pre></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am uploading one JS file using HTML input file tag. I am reading the data in Python. Since in my data var acb_messages is written, I am not able to parse it. And I want to use this variable name to get the data so I can remove it.
var acb_messages = {"messages": [{
"timestamp": 1475565742761,
"datetime": "2016-10-04 12:52:22 GMT+05:30",
"number": "VM-449700",
"id": 1276,
"text": "Some text here",
"mms": false,
"sender": false
}
]}
How can I parse it in Python and then how can I use it?
Two approaches that I would try if I were at your place -
Convert my .js file to .json file and then using method suggested by #Sandeep Lade.
Reading .js file as string, cropping out the value part and then using json.loads(<cropped part>) as suggested by #rahul mr.
Here is how to achieve 2nd solution -
import json
with open('your_js_file.js') as dataFile:
data = dataFile.read()
obj = data[data.find('{') : data.rfind('}')+1]
jsonObj = json.loads(obj)
What's happening here is that you are finding first reading your .js file (that contains js object that needs to be converted into json) as string, find first occurence of { and last occurence of }, crop that part of string, load it as json.
Hope this is what you are looking for.
Warning - Code works only if your js file contains js object only.
The options above are correct, but the JSON syntax in JS can be a little different than in Python:
example.js:
property.docs = {
messages: {
timestamp: 1475565742761,
datetime: "2016-10-04 12:52:22 GMT+05:30",
number: "VM-449700",
id: 1276,
text: "Some text here",
mms: false,
sender: false
}
};
Therefore we need one more tweak that I found at: How to convert raw javascript object to python dictionary?
The complete code should be:
import json
import demjson
with open('example.js') as dataFile:
data = dataFile.read()
json_out = data[data.find('{'): data.rfind('}')+1]
json_decode = demjson.decode(json_out)
print(json_decode)
import json
jsonfile=open("/path/to/json file")
data=json.load(jsonfile)
the above code will store will store your json data in a dictionary called data. You can then process the dictionary
I receive a jsonfrom the server when loading a page, and it gets populated in the page using Handelbars.java. Till now everything's fine.
However I would like to get that jsonobject and store it on a javascriptobject this is where I fail.
When I try to store it on a javascript object I do the following :
var jsObject = "{{output.items}}"; // the output.items is the JSON retrieved on the template
I get the following ("e; and line breaks interpreted) :
{
"profile": {
"name": "copernic",
"email": "copernic#cop.com"
}
....
}
When I should get the following (without line breaks interpreted) :
{
"profile": {
"name": "copernic",
"email": "copernic#cop.com"
}
....
}
So it throws me an error on javascriptUncaught SyntaxError: Unexpected token ILLEGAL.
When printing the json on the HTML template using <pre>{{output}}</pre> it looks just fine.
Do you have any idea about how can I store the jsonreturned from the server on page loading on a javascriptobject as I don't have much control of it since it's NOT coming with json?
Thank you.
Your server is serving a incorrect json format.
Your server needs to serve a json string, with double quotes.
{
"profile": {
"name": "copernic",
"email": "copernic#cop.com"
}
}
If you need to serve a well-formed json, you can try with Gson.
https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
Since the content output.items ist a string, this is how you can proceed.
eval("jsObject={" + object.items.replace(/"/g,'"')+"}");
I want use dForm in my MVC app.
When I try to build form from following json string it's ok.
var formdata = {
'action': 'index.html',
'method': 'get',
'elements':
[
{
"type":"select",
"name":"Name",
"caption":"Name",
"options":"first":{"html":"first","class":"active"},
"second":{"html":"second","class":"active"},
"selected":null
}
]
};
but when I use generated part for elements like:
var elements = {
"action": "index.html",
"method": "get",
"elements":
[
$('#jqgrid').jqGrid('getGridParam', 'userData')
]
};
$('#myform').buildForm(elements);
I get following error from dform:
uncaught exception: No element type given! Must always exist.
But I am sure that "elements" tag is the same as I posted in first example.
I have found that in firebug I can see the getted string userData for jqGrid in following format for ex.:
"userdata":"{\"type\":\"select\",\"name\":\"Name\",\"caption\":\"Name\",\"options\":{\"first\":\"first\" .....
I generate userData from JObject.
Maybe there is the problem. I have tried to replace the escaping character '\' but with no success.
That format doesn't look right. It is probably trying to convert
{ "userdata" : "JSON String" }
From what I can tell you probably have to do:
JSON.parse($('#jqgrid').jqGrid('getGridParam', 'userData').userdata);
If that doesn't do it, check out the Google Group, it is probably easier to help you there.