Parsing JSON response - javascript

I am new to using JSON. On subscribing to a webservice I receive a json response as given below.
1024760833990-36891Customercustomer realtime20110914 10:48:10NNNYYYYN{"hostName":"uat91w82m7","data":{"view":{"columnValues":[{"DisplaySymbol":"MSFT Jan 19 '13 $35 Call","Symbol":"MSFT--130119C00035000","Quantity":1.0,"Price":0.71,"ChangeValue":0.01,"ChangePercentage":1.41,"DaysGainValue":1.0,"PriceAdjusted":false}],"columnHeaderCodes":[1,2,3,4,11,5],"viewName":null,"quoteType":0,"accountNumber":"39903689","asOfDate":1316022555984,"totalMarketValue":"71.0","todaysGainValue":"1.0","annualGainValue":"0.0","pagination":{"nextPositionMarker":"","pageNumber":1,"posPerPage":500,"posDetailPerPage":50,"totalNumberofPositions":1,"markerLength":0},"viewType":3,"portfolioId":null,"customView":false,"displayNetWorth":1,"groupOptions":"G0","viewID":null,"widgetType":null,"columnHeaders":null,"totalPositionCount":0,"easternDaylight":true,"widget":false}},"smUser":"102476083","success":true,"sysdate":1316022555992,"message_info":null,"message_type":null}
I am trying to display certain parameters on my page. So how to I parse it.
ANSWER : just remove 1024760833990-36891Customercustomer realtime20110914 10:48:10NNNYYYYN through PHP or any other server side script and them parse it to jQuery, i'm damn sure it will do the job.

First paste your JSON into JSONLint.com to make sure it's valid JSON. What you provided in your question is not valid.
Secondly you can parse it with JQuery using parseJSON or with old skool JS using JSON.parse.

As long as you have a correctly formatted JSON string, all you have to do is use JSON.parse(string).
var JSON_string='{"name":"Jason","age":22}';
var JSON_object=JSON.parse(JSON_string);
console.log(JSON_object.name+' is '+JSON_object.age);

Related

JSON coming from server with quotes and regular expression

I'm analysing the way a server of a search page works (by inspecting element) and I could conclude that the request is sent with a POST with JSON as parameters.
Then I simulated the same POST (with the same parameters) using Insomnia. It was successful, but the response JSON came as string and inside the JSON, variables that uses quotes now uses \" instead.
An example of the JSON response:
"{\"AudienceRefiner\":{\"ItemCount\":0}}"
How can I read this on Python?
It is just an escape character, Consider using the ast library in order to parse it into an object.
literal_eval:
Safely evaluate an expression node or a Unicode or Latin-1 encoded
string containing a Python literal or container display.
import ast
st = "{\"AudienceRefiner\":{\"ItemCount\":0}}"
obj = ast.literal_eval(st)
print (obj)
>>> {'AudienceRefiner': {'ItemCount': 0}}
For more information about it, read ast.literal_eval
I am not sure where you got "{\"AudienceRefiner\":{\"ItemCount\":0}}" I guess that its not is python but webbrowser. Anyhow just use json if the json is in a string object
import json
di = json.loads("{\"AudienceRefiner\":{\"ItemCount\":0}}")

How to convert xml string in given format to json?

When i try to read xml data from Ajax response
xmlDoc = data[0].body;
alert(xmlDoc);
i got below string of xml string
"<VNET><ID>0</ID><UID>0</UID><GID>0</GID><UNAME>oneadmin</UNAME><GNAME>oneadmin</GNAME><NAME>vnet</NAME><PERMISSIONS><OWNER_U>1</OWNER_U><OWNER_M>1</OWNER_M><OWNER_A>0</OWNER_A><GROUP_U>0</GROUP_U><GROUP_M>0</GROUP_M><GROUP_A>0</GROUP_A><OTHER_U>0</OTHER_U><OTHER_M>0</OTHER_M><OTHER_A>0</OTHER_A></PERMISSIONS><CLUSTER_ID>-1</CLUSTER_ID><CLUSTER></CLUSTER><TYPE>0</TYPE><BRIDGE>bro</BRIDGE><VLAN>0</VLAN><PHYDEV/><VLAN_ID/><GLOBAL_PREFIX/><SITE_PREFIX/><RANGE><IP_START>192.168.5.2</IP_START><IP_END>192.168.5.254</IP_END></RANGE><TOTAL_LEASES>0</TOTAL_LEASES><TEMPLATE><DNS><![CDATA[192.168.5.1]]></DNS><GATEWAY><![CDATA[192.168.5.1]]></GATEWAY><NETWORK_ADDRESS><![CDATA[192.168.5.0]]></NETWORK_ADDRESS><NETWORK_MASK><![CDATA[255.255.255.0]]></NETWORK_MASK></TEMPLATE></VNET>"
so to avoid Html parsing in javascript. I want actual xml formate string.
ex:
"<VNET><ID>0</ID><UID>0</UID></VNET>"
want like
"<VNET><ID>0</ID><UID>0</UID></VNET>"
Any One please help me
The following answer would do what you're looking for, but it would be better to ensure the XML is not encoded in the original data response.
https://stackoverflow.com/a/14227660/463205

How to convert formatted string to regularly javascript dictionary?

I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ?
I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents.
Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

Trying to parse JSON string, unexpected number

I am trying to parse this JSON:
var json = '{"material":"Gummislang 3\/4\" 30 m (utanp\u00e5liggande sk\u00e5p)"}'
I run JSON.parse(json) but i get the error SyntaxError: Unexpected number when doing so. I have tried this in Google Chrome. I don't know what the problem is since I can take the JSON string and put it in any JSON validator and it claims that the JSON is valid. Shouldn't the browser be able to parse it?
You are inserting a JSON object representation into a JavaScript string without properly escaping the representation.
To avoid having to do this, remove the quotes you are adding around the representation, and skip the JSON.parse(json) – the default output from PHP's json_encode() is valid JavaScript when used in this context.
For security, you should specify the JSON_HEX_TAG option if possible. This will prevent cross-site scripting in cases where the JSON might end up inside a document parsed as XML. (And for XML documents, the JSON should be inside a CDATA section as well.)
You're validating the string literal, which is a valid JSON string containing invalid JSON. You need to validate the value of the string, which is not valid JSON.
If you paste the string value into a JSON validator, you'll see that the error comes from this part:
"material": "Gummislang 3/4"30m
The " needs to be escaped.

Is this valid JSON?

{"something":"1","mode":"true","number":"1234"}
Because I'm getting a 406 on expecting JSON.
It's being generated via Jersey, which is told that a method #Produces JSON. It's being received by a Dojo xhrGet which has JSON set as its handleAs.
EDIT - To clarify, I'm not interested in the code where I evaluate or anything like that. The question was very simple - is it valid JSON?
It is, but you've got both the boolean (mode) and numeric (number) elements as strings. Shouldn't it be:
{"something":"1","mode":true,"number":1234}
It is valid JSON if all values of the dictionary are Strings. This is also valid JSON:
{"something": 1, "mode": true, "number": 1234}
Usually, however, a 406 error happens when you ask for a response type (such as html or json) and the server cannot send it in that type. Why do you think the input is invalid?
I use a simple copy/paste tool called JASONLint ( http://www.jsonlint.com/ ) to test my mountains of JSON. You may dig it.
If you want to use the numbers directly, you shouldn't put them in quotes. It is valid JSON, but chances are that what you want to do is:
{"something":1,"mode":"true","number":1234}
You need to add more information if you want better answers.
EDIT: Eh... and yes, the boolean shouldn't be quoted either, unless you want to convert it yourself, for some reason.
yes this is valid JSON
although if you're planning on outputting this as the result of a HTTP request, you'll need to escape all the quotes
$str = "{\"something\":\"1\",\"mode\":\"true\",\"number\":\"1234\"}";
echo $str

Categories

Resources