I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)
Related
i have a webservice like this:
{"person":{"name account":"Jhon Doe","Image":"image/test","Adress":"New York 43","Recomendations":"40"}}
this is what i'm trying to do, when i print datos i get the whole json but when i try to print just the name or Image i don't get anything
var urll = "example.com/example";
var json;
var xhrr = Ti.Network.createHTTPClient({
onload: function() {
json = JSON.parse(this.responseText);
var datos = JSON.stringify(json);
var medicos = datos;
Ti.API.info("Json! "+datos);
}
});
xhrr.open('GET', urll);
xhrr.send();
i tried with datos[0].person, datos.person but nothing
You have to understand the difference between a string that contains a JSON representation of an object - and the object itself.
Your json variable contains the object (which is what JSON.parse(...) does - convert a text string to an object). On the object you can refer to the attributes as you discovered. You can do this in two ways:
json.person.Address
json.person['name account']
I would suggest that you try to avoid attributes with names that are not valid identifiers (as the latter of the two) as this makes it a little more difficult to use them - e.g. by not allowing the dot notation.
Your datos variable on the other hand contains the string representation of the json object (as JSON.stringify(...) does exactly that - convert an object to its string representation). This means that datos is the same as this.responseText (since you first parse it and then stringify it back).
So JSON.stringify(...) is a brilliant way to make the object "human readable" but you need the object to work with the data.
Hope this clarifies the terms a little ;-)
/John
i just find the solution:
Ti.API.info("Json! "+json.person.Recomendations);
I am running into an error parsing a json string with JSON.parse(...)
var str:String= '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Object = JSON.parse(str);
I can tell that I am getting the syntax wrong with constructing the JSON string but I have tried quite a few things before giving up. Any help with how to deal with collections would be great.
The following simple case works for me
var str:String= '{"test":"line1"}';
var propertySets:Object = JSON.parse(str);
Thank you
The syntax in the JSON string is correct. The way it is formatted will return an Array instance from JSON.parse(). The following code works for me:
var str:String = '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Array = JSON.parse(str) as Array;
trace(propertySets[0].AA); // prints "A1"
trace(propertySets[0].BB); // prints "32"
Shot in the dark since I don't know actionscript, but try wrapping the array in an object
var str:String= '{"objectArray":[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3","BB":"14"}]}';
using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for
what is the difference between json string and parsed json string?
for eg in javascript suppose i have a string in the json format say [{},{}]
parsing this string will also produce the same thing.
So why do we need to parse?
It's just serialization/deserialization.
In Javscript code you normally work with the object, as that lets you easily get its properties, etc, while a JSON string doesn't do you much good.
var jsonobj = { "arr": [ 5, 2 ], "str": "foo" };
console.log(jsonobj.arr[1] + jsonobj.str);
// 2foo
var jsonstr = JSON.stringify(jsonobj);
// cannot do much with this
To send it to the server via an Ajax call, though, you need to serialize (stringify) it first. Likewise, you need to deserialize (parse) from a string into an object when receiving JSON back from the server.
Great question. The difference is transfer format.
JSON is only the 'Notation' of a JavaScript Object, it is not actually the JavaScript 'object-literal' itself. So as the data is received in JSON, it is just a string to be interpreted, evaluated, parsed, in order to become an actual JavaScript 'Object-Literal.
There is one physical difference between the two, and that is quotation marks. It makes sense, that JSON needs to be a string to be transferred. Here is how:
//A JavaScript Object-Literal
var anObj = { member: 'value'}
//A JSON representation of that object
var aJSON = { "member":"value" }
Hope that helps. All the best! Nash
I think a parsed json string should be the string data into the actual javascript objects and data arrays (or whichever language the json string contains)
The JSON object contains methods for parsing JSON and converting values to JSON.
It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.
JSONParser parser = new JSONParser();
Object object = parser.parse(Message.toString());
JSONObject arObj = (JSONObject) object;
I am using the example code in flash. I want a single variable and not the whole text.
I have a dynamic textfield called OUTPUT on the stage.
var fl_TextLoader:URLLoader = new URLLoader();
var fl_TextURLRequest:URLRequest = new URLRequest("http://www.testing.com/Christmas.txt");
fl_TextLoader.addEventListener(Event.COMPLETE, fl_CompleteHandler);
function fl_CompleteHandler(event:Event):void
{
var textData:String = new String(fl_TextLoader.data);
OUTPUT.text = textData;
}
fl_TextLoader.load(fl_TextURLRequest);
The Christmas text file contents:
Var1=Jesus&Var2=Mary&Var3=Christmas
The OUTPUT comes out with the whole string. How do I get the url parameter values separately?
Like OUTPUT.text = textData.Var1; (<--- But this does not work.)
The .data property is just a string, the raw data returned by the HTTP call, so you will have to parse the variable-value pairs, either using simple .split() on the strings or using the URLVariables object, that can do the parsing for you:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html#decode()