Unable to parse stringified array within an array - javascript

I have this example code:
let testData= [{name:'Joshua',age:22,option:"[{value:'test'}]"},{name:'Ali',age:200,option:"[{value:'test2'}]"}]
let parsedData=JSON.parse(testData[0].option);
console.log(parsedData);
Testing my code using this site: https://es6console.com/
It seems that I'm unable to parse & log the data at all.
Any ideas why this is happening?

Your option string is not following the JSON specs: in JSON every key and string value needs to be enclosed in double quotes. So this would work:
let testData= [{
name: 'Joshua',
age: 22,
option: '[{"value": "test"}]'
}, {
name: 'Ali',
age: 200,
option: '[{"value": "test2"}]'
}];
let parsedData = JSON.parse(testData[0].option);
console.log(parsedData);

I think the issue is that JSON object's fields should be wrapped in double-quotes.
E.g.
let testData = [{name:'Joshua',age:22,option:`[{"value":'test'}]`},{name:'Ali',age:200,option:`[{"value":'test2'}]`}]

Related

What's the best way (ES6 allowed) to extract values from an array and convert them to a string?

I'm trying to take an array like so:
location: [
{Id: "000-000", Name: "Foo"},
{Id: "000-001", Name: "Bar"},
..etc
]
What's the most efficient/cleanest way to pull out the Ids and combine them into a single string while also appending in front of each value a static string ("&myId=")?
More succinctly, what's the most efficient way to turn the above array into the following end-result:
&myId=000-000&myId=000-001
As stated in the title, ES6 is acceptable to use if it offers the best method for accomplishing this.
Use reduce, extracting each Id:
const location2 = [{Id: "000-000", Name: "Foo"}, {Id: "000-001", Name: "Bar"}];
console.log(
location2.reduce((a, { Id }) => `${a}&myId=${Id}`, '')
);
While this is pretty clean and only requires iterating over each item once, in terms of efficiency, for loops are still more performant if you have a huge number of items in the array:
const location2 = [{Id: "000-000", Name: "Foo"}, {Id: "000-001", Name: "Bar"}];
let output = '';
for (let i = 0, { length } = location2; i < length; i++) {
output += '&myId=' + location2[i].Id;
}
console.log(output);
In this particular case, it looks like you’re trying to concatenate URL parameters.
You can iterate over the location array and use the appropriate set of APIs for this: URLSearchParams and URL.
In particular, you’re looking for the append method, which allows mapping multiple value to the same key.
const params = new URLSearchParams(),
locationArray = [
{
Id: "000-000",
Name: "Foo"
},
{
Id: "000-001",
Name: "Bar"
}
];
locationArray.forEach(({ Id }) => params.append("myId", Id));
console.log("Result as a string:", String(params));
console.log(`Explicitly calling \`String\` is usually not needed, since ${params} can just be interpolated, concatenated, or coerced to a String like this.`);
console.log("Result inside a URL:", String(Object.assign(new URL(location), { search: params })));
console.log("Result as a URLSearchParams object (look in the browser console (F12) for better formatting):", params);
But in general, using map and join seems efficient enough.
const staticString = "&myId=",
locationArray = [
{
Id: "000-000",
Name: "Foo"
},
{
Id: "000-001",
Name: "Bar"
}
],
result = locationArray.map(({ Id }) => staticString + Id).join("");
// Or:
// result = staticString + locationArray.map(({ Id }) => Id).join(staticString);
console.log(result);
In the alternative, the first staticString may also be changed to "?myId=", since this looks like query parameters.
But it’s important to use the URLSearchParams API if you’re actually using URL parameters, so that the data is correctly encoded.
Try both approaches with one of the Ids having the value "1&myId=2" and you’ll quickly notice the benefit of the URLSearchParams API.
This API also needs to be used to decode everything again.

Asynchronous Query JSON object

I have been playing around with a module from NPM called JSON-Query, I originally able to make the module function with JSON embedded in my js.
I have spent about two days attempting to make it query JSON that is external and in a JSON file.
The original code that was functioning looked something like this.
var jsonQuery = require('json-query')
var data = {
people: [
{name: 'Matt', country: 'NZ'},
{name: 'Pete', country: 'AU'},
{name: 'Mikey', country: 'NZ'}
]
}
jsonQuery('people[country=NZ].name', {
data: data
}) //=> {value: 'Matt', parents: [...], key: 0} ... etc
I was able to query the internal JSON to find the key I was looking for.
I realized I need the ability to update the JSON while the code is live, so I moved the JSON to its own file.
Currently my main JS file looks like this.
var jsonQuery = require('json-query');
var fs = require('fs');
function querydb(netdomain){
fs.readFile('./querykeys.json', 'utf8', function (err, data) {
if (err){console.log('error');}
var obj = JSON.parse(data);
console.log(jsonQuery('servers[netshare=Dacie2015].netdomain', {
obj: obj
}));
});
}
querydb();
My JSON file that contains the json looks like this.
{
"servers": [
{"netdomain": "google.com", "netshare": "password", "authip":"216.58.203.46"},
{"netdomain": "localhost", "netshare": "localghost", "authip":"127.0.0.1"},
{"netdomain": "facebook.com", "netshare": "timeline", "authip":"31.13.69.228"}
]
}
The issue I have ran into, I am unable to query the JSON anymore, when the function QueryDB() is ran, no matter what is in the place to query the JSON, i get no response locating my key.
Currently the response I get from the server when i try to query the JSON file is
{ value: null,
key: 'netdomain',
references: [],
parents: [ { key: 'servers', value: null }, { key: null, value: null } ] }
To be abundantly clear, i believe my issue is the way i call my object into play, i have played with the structure of the JSON-Query and have been unable to accomplish being able to isolate a key.
Any help on this would be amazing, the module that i am working with can be found on npm at [NPM]https://www.npmjs.com/package/json-query
Thank you
I think this is just a typo. Shouldn't this:
obj: obj
be this?
data: obj

JSON.stringify set root element

I want to convert my object into a JSON String where the root element should be the name of my object.
var data = {
name: 'qwertz',
age: 23,
skills: [
'html', 'css'
]
}
var json = JSON.stringify(data);
The output is:
{"name":"qwertz","age":23,"skills":["html","css"]}
But I want this:
{"data":{"name":"qwertz","age":23,"skills":["html","css"]}}
Can someone give me a hint how to reach this? Thanks you :)
As simple as that:
var json = JSON.stringify({ data: data });
Try this
JSON.stringify({'data':data})

How can I save an empty array into mongodb using js

Basically I got my app up an running but I'm stuck with a problem: if I pass an object that contains an empty array to be saved, the array is not saved into the db. I'm not sure this is a problem in js or the mongo driver, but in order to save the empty array I need to pass the array like so: products: [''].
This is the structure of my mongo document:
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'string',
products: [
{
name: 'string'
price: integer
}
]
}
]
So in my front-end I'm grabbing the whole document through an ajax call pushing a new object into the subcategories array. The new object looks like this:
{subcategory:'string', products:['']}
And this works okay until I need to insert a new object inside the array: Because I've grabbed the whole object, pushed the new object to the array, the previous one looks like this:
{subcategory: 'string'}
Having lost the mention to products:[] array in the process.
How can I get around this? I need to be able to have empty arrays in my object.
EDIT
What I did on front end: Got the whole object with $.get which returned:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
}
];
Then on the front end I've pushed the new object category inside the subcategories array:
data.subcategories.push({subcategory: 'Subcategory2', products: ['']})
Where subcat was a string with the category name. On my db I could see that I've successfully added the object:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
},
{
subcategory: 'Subcategory2'
products: []
}
];
The problem was when I wanted to add another subcategory, the previous one return empty:
var obj =
_id: ObjectId(...),
name: 'String',
subcategories: [
{
subcategory: 'Subcategory1',
products: [
{
name: 'string'
price: integer
}
]
},
{
subcategory: 'Subcategory2'
},
{
subcategory: 'Subcategory3'
products: []
},
];
Because at some point the empty array was removed from the object. Like I said, I did fix this in the front end, so the error jade was throwing has been addressed, but I still find odd that the products: [] was being removed from the document.
I'm new to MongoDb and node, not to mention that I'm also new with JS, so it might well be a feature that I'm unaware of.
When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.
Incase of empty arrays try posting as
Array[null];
instead of Array[];
This will be working fine
When passing empty arrays to Mongo they are interpreted as empty documents, {}. Zend Json encoder will interpret them as empty arrays []. I understand that it's not possible to tell which one is correct.
In my view it's more logical that the actual php array (when empty) is interpreted as an array in MongoDB. Although that will require something else to identify empty documents it's still more logical than the current behaviour.
A possible solution would be to introduce a new object, MongoEmptyObject (or using the stdObj) whenever one want to introduce an empty object.
Meanwhile, a workaround is to detect empty arrays in php, and inject a null value $arr[0] = null;
Then the object will be interpreted as an empty array in mongo.
The workaround works both in PHP and in the mongo console. Question: does json allow for arrays with null values? If so, then the workaround is a sign of another bug.
PHP:
if (is_array($value) && empty($value))
{ $value[0] = null; }
Mongo Console:
var b =
{hej:"da", arr: [null]}
db.test.save(b);
db.test.find();
{"_id" : "4a4b23adde08d50628564b12" , "hej" : "da" , "arr" : []}

Adding to a JSON string

I have a JSON string as follows:
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
It is generated after calling this function in KnockOut:
self.save = function() {
var dataToSave = $.map(self.lines(), function(line) {
return line.product() ? {
TypeName: line.category().TypeName,
TypeID: line.category().TypeID
: undefined
});
alert(JSON.stringify(dataToSave));
However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:
{
"Name":"Mark",
"Email":"me#me.com",
"Tel":"0123456789",
"Rooms":
[
{"TypeName":"Double","TypeID":14},
{"TypeName":"Single","TypeID":43},
{"TypeName":"Family","TypeID":7}
]
}
Is there a proper way of adding this information to the JSON, or is it just as simple as:
var toSend = "{\"Name\":\"Mark\":\"Email\":\"me#me.com\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}";
Thank you,
Mark
Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.
Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?
var toSend = JSON.stringify({
Name: "Mark",
Email: "me#me.com",
Tel: "0123456789",
Rooms: dataToSave
});

Categories

Resources