JavaScript parsing a JSON file - javascript

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());

Related

Creating Function to Parse JSON Data using substring

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.

Adding a new array element to a JSON object

I have a JSON format object I read from a JSON file that I have in a variable called teamJSON, that looks like this:
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}
I want to add a new item to the array, such as
{"teamId":"4","status":"pending"}
to end up with
{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}
before writing back to the file. What is a good way to add to the new element? I got close but all the double quotes were escaped. I have looked for a good answer on SO but none quite cover this case. Any help is appreciated.
JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON
var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
First we need to parse the JSON object and then we can add an item.
var str = '{"theTeam":[{"teamId":"1","status":"pending"},
{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
var obj = JSON.parse(str);
obj['theTeam'].push({"teamId":"4","status":"pending"});
str = JSON.stringify(obj);
Finally we JSON.stringify the obj back to JSON
In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.
elementToPush = [1, 2, 3]
if (!obj.arr) this.$set(obj, "arr", [])
obj.arr.push(elementToPush)
(This answer may not be relevant to this particular question, but may help
someone else)
Use spread operator
array1 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Organization"
}
];
array2 = [
{
"column": "Level",
"valueOperator": "=",
"value": "Division"
}
];
array3 = [
{
"column": "Level",
"operator": "=",
"value": "Country"
}
];
console.log(array1.push(...array2,...array3));
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<i class="fa fa-shopping-cart"></i>Add to cart'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
How do I store a simple cart using localStorage?

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 JSON parse by a given key without looping

Given a JSON string as this:
{
"__ENTITIES": [
{
"__KEY": "196",
"__STAMP": 1,
"ID": 196,
"firstName": "a",
"middleName": "b",
"lastName": "c",
"ContactType": {},
"addressCollection": {
"__deferred": {
"uri": "/rest/Contact(196)/addressCollection?$expand=addressCollection"
}
},
"__ERROR": [
{
"message": "Cannot save related entity of attribute \"ContactType\" for the entity of datastore class \"Contact\"",
"componentSignature": "dbmg",
"errCode": 1537
}
]
}
]
}
Is there a method to get just the __ERROR record, I know I can use
var mydata = json.parse(mydata) and then find it from the mydata object. But I was hoping there was a method to only return the ERROR field something like
json.parse(mydata, "__ERROR") and that gets only the information in the __ERROR field without turning the whole JSON string into an object
"Is there a method to get just the __ERROR record, I know I can use var mydata = json.parse(mydata) ... But I was hoping there was ... something like json.parse(mydata, "__ERROR")"
There may be libraries that do this, but nothing built in. You need to write code that targets the data you want.
The closest you'll get will be to pass a reviver function to JSON.parse.
var errors = [];
var mydata = JSON.parse(mydata, function(key, val) {
if (key === "__ERROR")
errors.push(val);
return val
});
without turning the whole json string into an object
That's hardly possible, you would need some kind of lazy evaluation for that which is not suitable with JS. Also, you would need to write your own parser for that which would be reasonable slower than native JSON.parse.
Is there a method to get just the __ERROR record
Not that I know. Also, this is an unusual task to walk the whole object tree looking for the first property with that name. Better access __ENTITIES[0].__ERROR[0] explicitly.
If such a function existed, it would have to parse the whole thing anyway, to find the key you're looking for.
Just parse it first, then get the key you want:
var mydata = JSON.parse(mydata);
var errorObj = mydata.__ENTITIES[0].__ERROR[0];
If you want, you may create your own function:
function parseAndExtract(json, key) {
var parsed = JSON.parse(json);
return parsed[key];
}

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"]}

Categories