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"]}
Related
I have following JSON array in my code
jsonList = [{"catName":"Carrom"}, {"catName":"Rugby"}]
In my case I want it to be look like this as a single JSON
{ "catName": "Carrom", "catName": "Rugby" }
How can I convert the abov JSON array to a single JSON ? What is the best way to do it ?
Maybe keep as an array of objects and use lodash to filter?
var catArray = [{"catName":"Carrom"}, {"catName":"Rugby"}];
_.find(catArray, { 'catName': 'Carrom' });
This will return any elements that match that query.
Maybe this could work for you
// Do this for every json
var attributes = Object.keys(json1)
for (var i = 0; i < attributes.length; i++) {
jsonresult[attributes[i]] = json1[attributes[i]]
}
According to the above comment by #JohannesReuter I changed my $match as follows now it works fine.
Thanks everyone for the help
Change in my api
`"$match": {
"category": { "$elemMatch": { "catName": { "$in": ["Chess", "Rugby"] } }
},
}`
Now I'm converting my json to this ["Chess", "Rugby"]
I've searched online a lot, but did not find anything. The questions here seem to address mostly php, so hopefully someone can help me with javascript.
Basically I am reading a text file and converting every line into a JSON object. I use .split() to turn the line into an array. However, when I do that, the array encloses the individual strings in single quotes. When I print the resulting object, it also has the values in single quotes. However I need them to be in double quotes for JSON. This might be a really stupid problem, or not a problem at at all, but I was not sure how to go about it. My code and terminal output are below.
Thank you in advance!!
lineReader.open('test.txt', function(reader){
num=0;
while (reader.hasNextLine()){
reader.nextLine(function(line){
//console.log(line);
line = line.toLowerCase();
lineArr = line.split('","');
//console.log(lineArr);
var last = lineArr.length - 1;
lineArr[0] = lineArr[0].slice(1);
lineArr[last] = lineArr[last].replace('"\r', '');
if (lineArr[last].slice(-1) === '"'){
lineArr[last] = lineArr[last].replace('"', '');
};
//console.log(lineArr);
if(lineArr[0] === 'Name'){
biz['Columns'] = lineArr;
} else{
var id = 'biz-' + num
biz[id] = {
"value": {
"name": lineArr[0],
"address": lineArr[1],
"city": lineArr[2],
"province": lineArr[3],
"postal": lineArr[4] }
};
};
});
num++;
}
console.log(biz);
});
Output:
{ 'biz-0':
{ value:
{ name: 'name',
address: 'address',
city: 'city',
province: 'province',
postal: 'postal code' } } }
I'd suggest not attempting to build your own parser... use JSON.parse() and/or JSON.stringify(); instead. If you need to support older IE versions (or are forced to render in quirks mode)... include Crockford's json2.js https://github.com/douglascrockford/JSON-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.
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());
I'm having an issue. I want to have a static dict
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
There are a lot of entries, and I want to have an easy access to all of them in case I need to change their value. Because of this, I don't like the single-line declaration.
As an alternative, I did manage to do the following, since multi-line text is allowed in Javascript:
var dict = {};
var loadDict = function() {
text = "aaa,true\n\
aab,false\n\
aac,false\n\
aad,true\n\[...]";
var words = text.split( "\n" );
for ( var i = 0; i < words.length; i++ ) {
var pair = words[i].split(",");
dict[ pair[0].trim() ] = pair[1].trim();
}
}
Is there a better/more elegant way of having a multi-line declaration of a dict?
note: Creating multiline strings in JavaScript is a solution only for strings. it doesn't work with a dict.
edit: I was adding a '\' at the end of each line. That was the issue. thanks.
var myDict = {
"aaa": true,
"aab": false,
"aac": false,
"aad": true,
[...]
};
I hope this is what you meant, because it's basic Javascript syntax.
Also, if for some reasons you want to "store" simple objects (made of strings, numbers, booleans, arrays or objects of the above entities) into strings, you can consider JSON:
var myDictJSON = '{\
"aaa": true,\
"aab": false,\
"aac": false,\
"aad": true,\
[...]
}';
var myDict = JSON.parse(myDictJSON);
Support for JSON is native for all the major browsers, including IE since version 8. For the others, there's this common library json2.js that does the trick.
You can also convert your simple objects into string using JSON.stringify.
that's easy-
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true
};
please remember, don't place the curly bracket in the next line.
i like responses. Please respond
This (a complex data structure containing both "string" and "booleans"):
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
Can be expressed like this:
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true,
[...]
};
Similarly, this:
var myBigHairyString = "Supercalifragilsticexpialidocious";
Can be expressed like this:
var myBigHairyString =
"Super" +
"califragilstic" +
"expialidocious";