Getting an error on JSON.parse - javascript

I was reading an article by Derick Bailey Don’t Return A JSON Document From The toJSON Method
I was trying to convert the following JSON object into Javascript:
var userJSON = "{\"firstName\":\"Derick\",\"lastName\":\"Bailey\"}";
var parseOnce = JSON.parse(userJSON.to_json).first;
var userObject = JSON.parse(parseOnce.to_json).first;
When I run the code I get a "SyntaxError: Unexpected token u"
Here is a jsbin of the same code https://jsbin.com/zugojoyaro/edit?js,console

this is a copy & paste problem from the blog post... (and a small error in the blog post, itself)
var userJSON = "{\"firstName\":\"Derick\",\"lastName\":\"Bailey\"}";
var parseOnce = JSON.parse(userJSON);
this works... but the code you have:
var parseOnce = JSON.parse(userJSON.to_json).first;
includes a .to_json and a .first attribute that don't exist. it looks like your trying to use ruby code on a JavaScript object

Related

Flask: python object to json triggering error when read by javascript

I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.
You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});

Node.js: Parsing a json-ld / JSON with "#"-symbol

I have a JSON that looks like this:
{"marker":[{"#attributes":{"start":"Im Berge",
"finish":"Eichelberger Stra\u00dfe"
...
I am trying to parse the attributes inside the "#attributes", but have not found a way to do it. What I tried so far:
const fs = require('fs');
var jsonObj = JSON.parse(fs.readFileSync('route1.json', 'utf8'));
console.log(jsonObj['#attributes']);
Also tried the same with
console.log(jsonObj.marker['#attributes']);
Neither of which work. I understand that this is supposed to be a json-ld and that I'm supposed to parse an object with an "#" sign with ['#attributes'], but either way I always get an error or undefined. I got the JSON from an API I wanna use and it is in there multiple times, so I have no way around it.
.marker is an array so:
console.log(jsonObj.marker[0]['#attributes']);
But you may want to loop through it:
jsonObj.marker.forEach(marker => console.log(marker['#attributes']));
You can require a JSON file, instead of JSON.parse & fs.readFileSync
var jsonObj = require('./route1.json');

append method using the from inside an Jquery $getJSON

Ok, so I have 3 files,
First a JSON file that tells me all the information that I need,
A Html file that gives me like a skeleton of where to put all the javascript
A javascript file that will hook up the information from the JSON and put into the html.
So my HTML is something like:
<div class="hello">
<h2>Name</h2>
</div>
My JSON is this with root to data/bio.json:
{
"name" : "Olivia Palito",
"age" : "23"
}
My Javascript is like this:
var mockup = '<div class="work"></div>';
var mockup02 = '<div>%data%</div>';
var $addItem01 = $(".hello");
var $addItem02 = $(".work");
var jsonRoot = 'data/bio.json';
$.getJSON(jsonRoot, function(data){
var addMe = mockup.replace('%data%', data.name);
$addItem01.append(mockup);
$addItem02.append(addMe);
});
Now the problem,
When I run this on the browser, I can add the first mockup, and it will add the <div class="work"></div> but when I try to add also the addMe, it doesn't show anything.
What am I missing here?
And if I put console.log(data); it will show something, which means that I am receiving the file, but it just not adding to the html, because I can add also static text, instead of using the replace method, and won't add the content.
var mockup02 = mockup.replace(%data%, data.name);
It does not work because that is not valid JavaScript.
Open up the console and you should see the error
Uncaught SyntaxError: Unexpected token %
You need to make it a regular expression
var mockup02 = mockup.replace(/%data%/, data.name);
or a string
var mockup02 = mockup.replace("%data%", data.name);
And the second reason it fails is you are selecting the element with the class work before it is added to the page. It does not magically find the element.
Switching it to and it will add it.
$(".work").append(addMe);

xPages - set javascript variable by reading JSON from URL

I have an xAgent (based on JSONandRest example in openntf by Nikolas Heildoff) which returns me a json. this xpage is nothing by there is a call to java method which returns JSON.
My problem is to have this JSON read into a JS variable so I am able to play with it.
I would like to do something like:
var myJson = getJson("Json.xsp")
Thanks in advance
Arun
You can use the fromJson method:
var json = "{a:'123', b: 'abc'}";
var obj = fromJson( json );
println( obj.a );
This sends 123 to the console.

AJAX post JSON data from Javascript to Grails

I'm trying to POST JSON formatted data from Javascript (using Prototype) to Grails. My Javascript code is:
var JSONObject = new Object;
JSONObject.id = "23";
JSONObject.name = "Test 1";
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'testController', action:'receiveJson')}";
new Ajax.Request(url, {
method:'post',
contentType:'application/json',
parameters:JSONstring,
asynchronous:true,
onSuccess: function (req) {
sendInfoResponse(req.responseText);
}
});
and the code in my Grails controller is:
def receiveJson = {
def json = request.JSON;
}
However, the 'json' variable appears to be empty in my tests. I'd be so grateful if someone could explain what I'm doing wrong. Many thanks.
In your Ajax.Request options change
parameters:JSONstring,
to
postBody:JSONstring,
The problem with using parameters is that it URL encodes the data so that the request body ends up looking like this:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
Instead of the desired (which is what you get with postBody):
{"id":"23","name":"Test 1"}
Good question mfloryan - I was doing the testing manually, i.e. not as part of a unit or integration test.
Thanks very much for the help hvgotcodes. I made the changes to my code as you have suggested, but unfortunately to no avail. Interestingly, if I print request.JSON I get {}, whereas if I print request.json I get null.
EDIT: By 'printing' I mean using: request.JSON.toString()
EDIT: Thank you all so much for the help. Once I'd made the final change John Wagenleitne suggested the code began working properly. I'm very grateful indeed for all your help.
I don't think you are invoking the Ajax.Request correctly. From the documentation, the parameters option:
"The parameters for the request, which will be encoded into the URL for a 'get' method, or into the request body for the other methods. This can be provided either as a URL-encoded string or as any Hash-compatible object (basically anything), with properties representing parameters."
I think you need to do something like
...
parameters: {json: JSONString}
...
and then in your controller
request.json
note the form of the parameters object literal - it tells the Prototype library to make the request key 'json' and the request value be the json string. You access the key off the request object in the controller.
EDIT -- I just realized you're javascript block is jacked up.
This:
var JSONObject = new Object;
should be something like
var JSONObject = new Object();
...
you might also be able to do just an object literal, so
var jsonObject = {};
....

Categories