Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below
Answer from JonoW on Stack OverflowScript for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below
I made it that way:
if I have:
var jsonArg1 = new Object();
jsonArg1.name = 'calc this';
jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
jsonArg2.name = 'calc this again';
jsonArg2.value = 2.73;
var pluginArrayArg = new Array();
pluginArrayArg.push(jsonArg1);
pluginArrayArg.push(jsonArg2);
to convert pluginArrayArg (which is pure javascript array) into JSON array:
var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))
Convert JSON to Javascript Array Object - node.js - Stack Overflow
Convert Array to Json [duplicate]
Convert Json object to array in nodejs - javascript
How to convert from array of json object to String in Nodejs?
You can try Javascript's inbuilt functions like this:
var fs = require('fs');
var results = JSON.parse(fs.readFileSync('games.json', 'utf8'));
function grabDataFromAGame(elem, index, array) {
// Grab the data from the game object you need
var gameObj = {};
gameObj.challengerScore = elem.challengerScore;
gameObj.defenderScore = elem.defenderScore;
gameObj.id = elem.objectId;
saveGameObjToFile(gameObj);
}
function saveGameObjToFile(gameObj){
var gameFile = fs.openSync('./gameObj-' + gameObj.id + '.json', 'w');
fs.writeSync(gameFile, JSON.stringify(gameObj));
}
results.results.forEach(grabDataFromAGame);
This code generated the following files:
~/salesman 542-> node so.js
~/salesman 543->
~/salesman 543->
~/salesman 543-> ll gameObj-*
-rw-r--r-- 1 neerajsharma staff 59B Jun 11 18:56 gameObj-pmiACGwe45.json
-rw-r--r-- 1 neerajsharma staff 59B Jun 11 18:56 gameObj-HqptXdYmQL.json
~/salesman 544-> cat gameObj-pmiACGwe45.json | python -m json.tool
{
"challengerScore": 18,
"defenderScore": 21,
"id": "pmiACGwe45"
}
~/salesman 545->
Note that it is not recommended to use sync calls with Node, because node is single-threaded and your application is blocked till the sync calls are complete.
An example of using forEach can be found here
Try:
results.results.forEach(function (result) {
console.log(result);
});
You should try to use the async calls. Node.js is really meant for asynchronous non-block I/O.
In modern browsers you can simply use JSON.stringify(someJSObject) to convert any JavaScript object (that includes arrays) to a JSON string.
To ensure it also works in less modern browsers, include https://github.com/douglascrockford/JSON-js/blob/master/json2.js on your page.
How about
var jsonString = JSON.stringify(myArray);
Your data is insode Photos object, and then you push in an empty array.
So when you find from the array, you need to get it from the correct position.
Correct code:
(function test(id) {
let PhotoData = "{\"Photos\":[{\"id\":\"Photo1\", \"Type\": \"Color\", \"Shade\": \"Grey\"}, {\"id\": \"Photo2\", \"Type\": \"Color\", \"Shade\": \"Red\"}]}"
let photoArray = []; //photoArray
let getPhoto = JSON.parse(PhotoData); //Converting to JSON object
console.log(getPhoto);
photoArray.push(getPhoto); //Pushing to arrayv so that search can be done
console.log(photoArray);
const foundPhoto = photoArray[0].Photos.find((photo) => photo.id == id);
console.log(foundPhoto );
})("Photo1");
Result:
{id: "Photo1", Type: "Color", Shade: "Grey"}
It's strange that you convert this object with photos back to a string with JSON.stringify() and then add that string to an array. See my suggestion below.
const existingArrayOfPhotos = [];
yamlString = `Photos:
- id: Photo1
Type: Color
Shade: Grey
- id: Photo2
Type: Color
Shade: Red`
const photoData = YAML.parse(yamlString);
existingArrayOfPhotos.push(...photoData.Photos)
const foundPhoto = existingArrayOfPhotos.find((photo) => photo.id == "Photo1");
console.log(foundPhoto);
<script src="https://cdnjs.cloudflare.com/ajax/libs/yamljs/0.3.0/yaml.min.js"></script>
Build up a JavaScript data structure with the required information, then turn it into the json string at the end.
Based on what I think you're doing, try something like this:
var result = [];
for (var name in goals) {
if (goals.hasOwnProperty(name)) {
result.push({name: name, goals: goals[name]});
}
}
res.contentType('application/json');
res.send(JSON.stringify(result));
or something along those lines.
You don't have JSON. You have a JavaScript data structure consisting of objects, an array, some strings and some numbers.
Use JSON.stringify(object) to turn it into (a string of) JSON text.
Edit: Try this:
var query = {"theArray":"[[],\"d\",\"B\",{},\"b\",12,\"A\",\"c\"]"};
var par = JSON.parse(query.theArray);
var stringArray = [];
for ( var i = 0; i < par.length; i++ ) {
if ( typeof par[i] == "string" ) {
stringArray.push(par[i]);
}
}
var jsonString = JSON.stringify( stringArray );
console.log(jsonString);
P.S. I didnt't pay attention. Your array was actually a string. Andrey, thanks for the tip.
The replacer parameter of JSON.stringify doesn't work quite like you're using it; check out the documentation on MDN.
You could use Array.prototype.filter to filter out the elements you don't want:
var arr = [[],"d","B",{},"b",12,"A","c"];
arr = arr.filter(function(v) { return typeof v == 'string'; });
arr // => ["d", "B", "b", "A", "c"]