This is driving me nuts and I'm hoping someone has encountered this & come up with a clean, elegant solution. When making a JSON request to the LinkedIn REST Api, the body comes back as a string with new-line characters. When I parse the string to JSON with JSON.parse it appears to create a JSON Object, but I can't access the values with dot notation using their relative keys. I have tried escaping the new line characters, a combination of JSON.stringify then parsing, etc. I cannot get this to work and it's obnoxious, though I'm sure there's a simple solution I'm overlooking. Here's the response from the LinkedIn API:
{"statusCode":200,"body":"{\n \"numConnections\": 152,\n
\"numConnectionsCapped\":
false\n}","headers":{"server":"Apache-Coyote/1.1","x-li-request-id":"myid","vary":"*","x-li-format":"json","content-type":"application/json;charset=UTF-8","date":"Tue,
10 Jan 2017 00:08:01
GMT","x-li-fabric":"prod-ltx1","transfer-encoding":"chunked","x-li-pop":"prod-ltx1","set-cookie":["lidc=\"b=TB70:g=489:u=129:i=1484006881:t=1484082637:s=AQG3LuLPqWuZiIoHGf2NqD8O7mRfdA4q\";
Expires=Tue, 10 Jan 2017 21:10:37 GMT; domain=.linkedin.com;
Path=/"],"x-li-uuid":"53NCd2VAmBSAAWKrrSoAAA=="},"request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"api.linkedin.com","port":443,"hostname":"api.linkedin.com","hash":null,"search":"?format=json","query":"format=json","pathname":"/v1/people/id=myid:(num-connections,num-connections-capped)","path":"/v1/people/id=myid:(num-connections,num-connections-capped)?format=json","href":"https://api.linkedin.com/v1/people/id=myid:(num-connections,num-connections-capped)?format=json"},"method":"GET","headers":{"authorization":"Bearer
mytoken"}}}
I'm trying to access the value with key "numConnections" but just can't get to the value.
Using JSON.parse(response.body) gets me this result:
{"numConnections":152,"numConnectionsCapped":false}
however I still cannot access the values associated with each key using
myObj.numConnections or any of the other notation I've tried. How can I get a valid JSON object out of this in NodeJS?
The result of parsing response.body is an object - on which you can use dot notation or bracket notation to access the values:
var parsedBody = JSON.parse(response.body);
parsedBody.numConnections //152
parsedBody['numConnections'] //152
Try
JSON.parse(JSON.stringify(response.body))
Well, this was stupid. I found that my issue was really with Express not allowing numeric values to be sent with res.send(num). For some reason there was no error in the console as a resulting and I was receiving an undefined value with the get request. Parsing the JSON was not the issue, but marked answer as valid. If anyone else is having this issue, you need to stringify numeric values when separating them from the object if you want to send them as a response in Express!
Related
The data is stored as an array of objects wrapped in a string that looks like this
["{\"x\"=>15, \"y\"=>7}", "{\"x\"=>14, \"y\"=>7}", "{\"x\"=>13, \"y\"=>7}", "{\"x\"=>13, \"y\"=>6}", "{\"x\"=>13, \"y\"=>5}", "{\"x\"=>13, \"y\"=>4}", "{\"x\"=>13, \"y\"=>3}", "{\"x\"=>12, \"y\"=>3}", "{\"x\"=>11, \"y\"=>3}"]
The reason it is stored that way is because when I was storing the data from a json, I had to convert what was wrapped in Action Parameters to a hash.
I took a look at How to convert a ruby hash object to JSON? and Parse JSON in JavaScript?, and my answer is not addressed.
First, the problem is that it would seem JSON does not parse anything wrapped in double quotations, nor with rocket hash notation, and so I am not able to convert to convert "{"x"=>15, "y"=>7}" to {"x"=>15, "y"=>7}.
Perhaps, I have to serialize the object, see where I get my data from here: How can I access the data for the snake object sent through JSON in my params?
Any ideas on what the right approach would be?
Following radiantshaw's lead, using either
eval("{\"x\"=>15, \"y\"=>7}")
or
JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))
I got the following: {"x"=>15, "y"=>7}, which is a Ruby object. However in order to convert this to a Javascript object, I also needed to convert it to json.
So by taking it one step further, I am able to parse it into json like so:
Put require 'json' in the .rb file, and then do {"x"=>15, "y"=>7}.to_json which will result in
"{\"x\":15,\"y\":7}".
The reason you're not able to convert to JSON because hash rocket is not a proper JSON syntax. Hash rocket is purely Ruby syntax.
What that means is that you somehow managed to take a Hash and convert it to a String. So the converted string is actually Ruby code and not JSON.
You could do...
eval("{\"x\"=>15, \"y\"=>7}")
... and it will return a Ruby Hash.
Or if you don't want to use eval due to security reasons, you can do...
JSON.parse("{\"x\"=>15, \"y\"=>7}".gsub('=>', ':'))
In netsuite i'm using the nlapiRequestURL to retrieve a JSON data from flexport, an overseas shipping company. I have have the data as a string(to my knowledge retrieving json data makes it a string) and want to turn it into an array of objects, but everything I have tried has resulted in various errors.
trying...
`var output = nlapiRequestURL(url,null,headers,"GET");
var split = JSON.parse(output.getBody());
response.write(split);`
gave me
{records=[Ljava.lang.Object;#7220fad}
and trying to show any element of split gave me undefined or that it cant read element from index.
I've ran the string through a JSON checker and it said it was a valid JSON file. I've done various variations of JSON.parse and looked tried Tostring. I've been working on this for a while and have no idea why I can't parse this information properly. Any help is appreciated.
You have parsed the result but then you are writing the parsed object which just gets you the object’s implementation dependent toString() output.
If you are just trying to echo the response re-stringify the parsed payload.
i know that there's so many questions about this but sorry im really confuse about this error...
i created a login page and i used ajax for the POST Request..what happens is when i used this
$.ajax({
url:'../ajax/checklogin.php',
type:'POST',
dataType:'JSON',
data:$('form').serialize(),
success: function(result){
$.post("../www/login.php",{ users_id: JSON.parse(result.users_id)}).done(window.location.href='../www/index.php');
}
});
the $.post is working but when i tried to add another field to parse i got this error.. the error is on users_active.. for some reason i dont have any idea why i got the error
$.post("../www/login.php",{ users_id: JSON.parse(result.users_id),users_active: JSON.parse(result.users_active)}).done(window.location.href='../www/index.php');
the other field are fine but the only field that gives me error is the users_active.. i even check the json array that is being returned they are valid json...
JSON.parse() takes a string and turns it into a JavScript object.
You are lucky, that JSON.parse("12345") can be converted to new Number("12345"), which is indeed an integer.
result.users_active is already a JavaScript object (or array) or maybe a String, which not represents a JSON object, so the parse will result in a syntax error as stated in https://www.w3schools.com/js/js_json_parse.asp.
I assume, you need JSON.stringify(), but to assure that, you should post some code or your result object.
https://www.w3schools.com/js/js_json_stringify.asp
Edit: Now that I have seen the object, "active" is a simple string and you can't strip the quotes. So just use users_active: result.users_active.
JSON.parse doesn't remove quotes ("), but converts your data into objects, booleans or strings - if they were valid json before (not just the values of the properties, which you have passed). See here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you want to assure that you pass integers or strings (or whatever you need) to your ajax post, just use the adequate javascript functions, like parseInt() or String().
See here an example with your data:
var result = {
"id":"26",
"users_id":
"201710001",
"users_username":"123",
"users_active":"active"
};
$.post("../www/login.php", {
users_id: parseInt(result.users_id),
users_active: String(result.users_active)
}).done(window.location.href='../www/index.php');
I have a Java JSON Object, its format is [{a=b}], I am trying to pass this object into javascript as a JSON object but its missing " on both the key and value as well as having "=" instead of ":"
Is there a simple way of converting this JAVA JSON object to be consumable by different services?
Parsing is proving to be very complicated as the actual JSON is nested and the lack of quotations and the lacking of indications for nestedness.
Sample of 'JSON' data:
[{wwnType=Virtual, serialNumberType=Virtual, connections=[], modified=2016-10-29T19:00:04.457Z, macType=Virtual, category=server-profile-templates, serverHardwareTypeUri=/rest/server-hardware-types/32006464-D3C6-4B4E-8328-47A193C6116C, bios={overriddenSettings=[], manageBios=false}, firmware={firmwareBaselineUri=null, manageFirmware=false, forceInstallFirmware=false, firmwareInstallType=null}, boot={manageBoot=true, order=[CD, Floppy, USB, HardDisk, PXE]}, hideUnusedFlexNics=true, bootMode=null, state=null, affinity=Bay, localStorage={controllers=[]}, type=ServerProfileTemplateV1, status=OK, description=, eTag=1477767604457/1, serverProfileDescription=test, name=test, created=2016-10-29T19:00:04.428Z, enclosureGroupUri=/rest/enclosure-groups/e989621b-930e-40e7-9db0-a6ddbf841709, uri=/rest/server-profile-templates/db1dbdcc-4237-4452-acc3-cf9dfdc75365, sanStorage={manageSanStorage=false, volumeAttachments=[]}}]
Thanks
It's not going to be simple. However, I think you can do this without writing a full-fledged parser, as long as you're willing to write a tokenizer, or lexical analyzer, to break your input string into tokens. The basic plan could be something like:
Convert your input into a list of tokens. I don't know what the format of your input is, so you'll need to do your own analysis. A token would be something like a single character [, ], {, }, comma, =; or an identifier (a or b in your example, but I don't know what the possible valid formats are); or, maybe, a string literal in quotes, or a numeric literal, depending on what your needs are.
Go through the string and replace the tokens you need to. Based on your example, I'd say that after a {: if the first token after that is an identifier, put it in quotes; if the second token after that is =, change it to :; if the third token after that is an identifier, put it in quotes. The same could be true after a comma, but you'll need to keep track of whether the comma is a separator for a list of key-value pairs in an object, or a list of values in an array. For that, you may need to keep a stack that you push whenever you see [ or {, and pop whenever you see } or ], so that you know whether you're inside an object or an array.
After you're done replacing everything, concatenate the tokens back together. The result should be a well-formed JSON object.
This is just a rough outline, since I really don't know all your requirements. You'll probably have to adapt this answer to meet your exact needs. But I hope this helps as a general idea of how you could approach the problem.
Sorry, I don't think there's a simpler answer, except that you might want to look into parser generators (see Yacc equivalent for Java). I haven't actually looked at any in Java, so I don't know how simple they are to use. Please don't try to solve the whole thing with regexes. (Regexes will be useful for breaking your string into tokens, but trying to do more than that with regexes is likely to produce nothing but migraine.)
I think isn't json object. json object should be like this.
Example:
JSONObject obj = new JSONObject();
obj.put("a", "b");
obj.put("name", "your name");
Output: {"a": "b", "name":"your name"}
Passing into javascript
var obj = '{"a": "b", "name":"your name"}',
var json = JSON.parse(obj);
I am just trying to parse a Json document with a field Date like this:
´ death':Date('2007-03-17T04:00:00Z') using
com.mongodb.util.JSON.parse(document)
There is an exception when the value Date is encountered. Any help?
The key here is whatever has exported the data has done it wrong. Possibly someone has run something from the MongoDB shell and redirecting console output to a file. That is basically "doing it wrong".
There is a concept called MongoDB Extended JSON and has in fact been picked up in a few other areas, notably the EJSON project.What this tries to do is make sure that any exported JSON maintains "type" information to the BSON type identifier ( or other Object Type, in the purpose of EJSON ) so that a similar "extended JSON" parser can "re-construct" the object to it's intended form.
For a "date" object, the intented JSON representation is this:
{ "death": { "$date": "2007-03-17T04:00:00Z" } }
Since com.mongodb.util.JSON.parse is enabled with knowledge of the Extended JSON spec, then any such JSON contruct will result in a correct date object being constructed from the parsed data.
So what you have right now is just a "string". In fact, if it is not "quoted" like this:
´ { "death" : "Date('2007-03-17T04:00:00Z')" }
Then it is not in fact even valid JSON and would even need to be manipulated to a correct form before even a basic JSON parser would not error. At any rate, the result is just a "string" still, so you would need to make a regex match for the numerical data, then pass that to a date object construct.
Clearly the "best" thing to do here is to fix the "export" source of the data so that it is doing this date parsing to JSON in the correct extended way. Then the parser you are using will do the right thing.