Creating Function to Parse JSON Data using substring - javascript

i'm working in AS2 & it's looks like javascript alot
JSON
{
"name": "Tom",
"age": 20,
"state": "usa"
}
now i cant parse JSON data in AS2 & need workaround function using substring
something like that below and i load json file using loadVars()
var _lv:LoadVars = new LoadVars()
_lv.onData = function(data)
{
var ex:Object = eval("data");
var JSONTOArray:Object = ex.toString().split(',');
var getname=JSONtoArray[0].substring(JSONtoArray[0].lastIndexOf('"name": "')+9,JSONtoArray[0].lastIndexOf('"'));
}
_lv.load("MyJSON_URL");
now need to build function like
getThis('name'); // return Tom
getThis('age'); // return 20
getThis('state'); // return usa

The best solution is to use existing parser, because
you will not have to write your own code
it probably has common syntax like JSON.parse and JSON.stringify

var abc={
"name": "Tom",
"age": 20,
"state": "usa"
};
console.log(abc['name']); //Tom
console.log(abc['age']); //20
console.log(abc['state']); //usa

To parse a json data using ActionScript 2, you can use the JSON.as class ( from JSON.org ), after putting it in the same directory as your .fla, you can use it like this :
import JSON;
var json = new JSON();
var loader:LoadVars = new LoadVars();
loader.onData = function(data)
{
trace(json.parse(data).name); // gives : Tom
}
loader.load('file.json');
Hope that can help.

Related

Convert String to Array of JSON Objects (Node.js)

I'm using Node.js and express (3.x). I have to provide an API for a mac client and from a post request I extract the correct fields. (The use of request.param is mandatory) But the fields should be composed back together to JSON, instead of strings.
I got:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": request.param('items')
};
and request.param('items') contains an array of object but still as a string:
'[{"name":"this"},{"name":"that"}]'
I want to append it so it becomes:
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": [{"name":"this"},{"name":"that"}]
};
Instead of
var obj = {
"title": request.param('title'),
"thumb": request.param('thumb'),
"items": "[{\"name\":\"this\"},{\"name\":\"that\"}]"
};
Anyone who can help me with this? JSON.parse doesn't parse an array of object, only valid JSON.
How about this:
var obj = JSON.parse("{\"items\":" + request.param('items') + "}");
obj.title = request.param('title');
obj.thumb = request.param('thumb');
JSON.stringify(obj);
Perhaps I'm missing something, but this works just fine:
> a = '[{"name":"this"},{"name":"that"}]';
'[{"name":"this"},{"name":"that"}]'
> JSON.parse(a)
[ { name: 'this' }, { name: 'that' } ]
Node#0.10.13
May be you have old library Prototype. As I remove it, bug has disappeared.
You can try the same code. Once in page with Prototype.js. Second time in new page without library.

JavaScript parsing a JSON file

I am using the following code to parse a single line of a JSON file:
var str = '{ "jobID": "2598752", "account": "TG-CCR120014", "user": "charngda",
"pkgT": {"mvapich2-new/1.2": { "libA": ["libmpich.so.1.1"], "flavor": ["default:pgi/7.2-5"] } },
"startEpoch": "1338608868", "runTime": "48", "execType": "user:binary", "exec": "IOR",
"numNodes": "4", "sha1": "755187bd8550881bb0c9951822e74a9a53c8d0f3", "execEpoch": 1336757832,
"execModify": "Fr, Ma, 1, 12:37:1, 2012", "startTime": "Fr, Ju, , 22:47:4, 2012",
"numCores": "64","sizeT": { "bss": "36224", "text": "3502656", "data": "128944" } }';
var obj = JSON.parse(str);
delete obj['flavor'];
delete obj['pkgT'];
var newstr = JSON.stringify(obj);
document.write(str);
However, I want to parse the entire 6000 line JSON file. How do i read the file line by line and delete the fields as I have done with the single line. I have zero experience with Javascript so I have no clue how to read a file or create a new file. I assume I would use some sort of array, but I am not sure. Can anyone help?
If your file looks like this:
[{"jobID": "1",...},{"jobID": "2",...},{"jobID": "3",...},...]
You can do something like this:
var objArray = JSON.parse(str);
for( var k=0; k<objArray.length; k++ ) {
delete objArray[k]['flavor'];
delete objArray[k]['pkgT'];
}
var newstr = JSON.stringify(objArray);
document.write(newstr);
Just add the complete file content to the str variable by copy and paste.
This solution won't help you if you need to do this on a regular basis !
Something like this will probably work. I haven't got a 6000 line JSON file to test it on, but it should at the least give you a clear idea where you should be going next with your solution.
Remember, JSON blocks are just ordinary javascript objects which are a data structure already with their own methods, so you can iterate over them by just using standard object iteration.
var bigObj = json.parse(jsonFile);
var objArray = [];
var newStr;
for (var obj in bigObj){
if (bigObj.hasOwnProperty(obj)){
delete obj['flavor'];
delete obj['pkgT'];
newStr = JSON.stringify(obj);
objArray.push(newStr);
}
}
document.write(objArray.join("/n").toString());

Access Data from Ajax Call Jquery

I am using Jquery Ui Autocomplete.
The problem I have is the data that is being returned from my api.
"{"d":{"results":[],"facets":{"facet_counts":{"Town":{"":0,"londonderry":136914,"london bridge":1,"london":8983316,"london colney":1}}},"__solr_time":3473457,"__ser_time":1564,"__t_time":1421,"__count":9120232,"__max_score":1.0}}"
I have run it through an online parser and it is valid, but I don't know how to access the list of towns with the corresponding number next to it.
Any help would be appreciated
I was able to access the Town "name" and number using:
var test = {
"d": {
"results": [],
"facets": {
"facet_counts": {
"Town": {
"": 0,
"londonderry": 136914,
"london bridge": 1,
"london": 8983316,
"london colney": 1
}
}
},
"__solr_time": 3473457,
"__ser_time": 1564,
"__t_time": 1421,
"__count": 9120232,
"__max_score": 1
}
}
for(var prop in test.d.facets.facet_counts.Town){
console.log(prop);
console.log(test.d.facets.facet_counts.Town[prop]);
}
Just run JSON.parse() on the string and then pull out the Town node.
var string; // the data string returned by API.
var dataObj = JSON.parse(string);
var Town = dataObj.d.facets.facet_counts.Town;
// access the properties as needed
var londonCount = Town.london;
var londonBridgeCount = Town['london bridge']; // need to use bracket notation to get this one

Need help in creating Json string in javascript

I am unable to create a Json string in the following format, please help. Where key value pair can be a number:
"tag_container": { "tag1": "Tag1", "tag2": "Tag2", ..... }
var uploaded = new Uploaded();
var str = "*#Hello* i *#am* writing a regexp *#h*";
var re = hash_parser(str);
uploaded.tag_list = new Array;
uploaded.tag_list.tag = new Array;
for(var i = 0; i < re.length; i++)
{
uploaded.tag_list[i] = new Object;
uploaded.tag_list[i].**tag** = re[i];
}
above code is giving in following format:
"tag_list":[{"**tag**":"*#Hello*"},{"**tag**":"*#am*"},{"**tag**":"*#h*"}]
I think maybe you might be confusing JSON with object literal syntax.
Instead of:
"tag_container": { "tag1": "Tag1", "tag2": "Tag2", ..... }
you should just be using normal JS syntax:
var tag_container = { "tag1": "Tag1", "tag2": "Tag2", ..... }
... but it's really hard to tell from your post. If you know anyone who can help you with your English, it really might help me (and others) understand this question better.
The easiest way to convert something into JSON is to use JSON.stringify.
var jsonString = JSON.stringify({ tag_container: { tag1: 'tag1', tag2: 'tag2' }});
stringify is available in all modern browsers. If you wish to support older versions, the JSON2 library is perhaps the best choice as it provides the same API as the official JSON spec.
I think what you're trying to do is something like this:
var reLen = re.length;
uploaded.tag_list = {};
for(var i = 0; i < reLen; i++)
{
uploaded.tag_list['tag' + (i+1)] = re[i];
}
This will output the format you wish to see, i.e.
'"tag_container": {"tag1": "*#Hello*", "tag2": "*#am*", "tag3": "*#h*"}'
Thank you all for the all reply and guide my problem is solved in some other way I am sending json string to cross domain
string = "hi #group1 #group2 *user1 *user2 #fs #ffsd #fsdf";
and generated json string is
{"raw_msg":"hi #group1 #group2 *user1 *user2 #fs #ffsd #fsdf","msg_type":"group","top_msg_id":0,"file_container":{"file1":{"id":"","file_name":"","uri":""},"file2":{"id":"","file_name":"","uri":""}},***"tag_list":["fs","ffsd","fsdf"]***,"link_list":"","image_container":{"image1":{"id":"","name":"Name","uri":""},"image2":{"id":"","name":"Name","uri":""}},"attached_thread":{"thread1":{"title":"","top_id":"","last_id":""},"thread2":{"title":"","top_id":"","last_id":""}},"to_user":["user1","user2"],"to_group":["group1","group2"]}

Beginner JavaScript: Working with JSON and Objects in JavaScript

I have some JSON returned to the browser like this "product":
{ "Title": "School Bag", "Image": "/images/school-bag.jpg" }
I want this data to be a "Product" object so I can use prototype methods like a toHTMLImage() that returns a HTML image representation of the product:
function Product() { }
Product.prototype.toHTMLImage = function() { //Returns something like <img src="<Image>" alt="<Title>" /> }
How do I convert my JSON results into a Product object so that I can use toHTMLImage?
Simple, if I got it,
var json = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
function Product(json) {
this.img = document.createElement('img');
this.img.alt = json.Title;
this.img.src = json.Image;
this.toHTMLImage = function() {
return this.img;
}
}
var obj = new Product(json); // this is your object =D
var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
var newstuff = new Product();
for(i in stuff) newstuff.i = stuff[i];
Not sure if this will work, but give it a shot:
var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
stuff.prototype = Product;
Maybe this page will be usefull : http://www.json.org/js.html
For converting JSON to an object you can use
window.JSON.parse(jsonText) in Mozilla (check Chrome and Opera, I don't know how it works there.)
In Internet Explorer you can use (new Function("return " + jsonText))(),
but you should check the JSON for non-valid symbols, google it.

Categories