How to parse a JSON array string in JavaScript? - javascript

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?

filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];

With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.

With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo

You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

Related

How to get the filtered object into the json-server when an end user does a rough search?

I am using json-server as my fake API data. I am implementing the search functionality to it. I created an endpoint like this -
getData : ( searchTerm : string ) => axios.get(`http://localhost:3000/books?=${searchTerm}`).then((response) => setData(response));
and I am utilizing into my input field to get the searched results.
Let's say My json object coming back from the Json-server is as follows -
[
{
"Id": 1,
"name" : "car"
},
{
"Id": 2,
"name" : "bike"
},
{
"Id": 3,
"name" : "ninja bike"
}]
now, the problem is , when I search for "car", it gives me the json result.
but, when I search for "brand new car", it should give me the "car's" object at least, as word "car" is a match. but it is giving me [], empty array.
So please suggest me how could i look for specific words into my json-server's data?
so that whenever , the end user even make a vague unstructured search, it should look for specific words like "car", in this case and return that car object.
You can make a simple filter to check if your string is in there
let json = [{
"Id": 1,
"name": "car"
},
{
"Id": 2,
"name": "bike"
},
{
"Id": 3,
"name": "ninja bike"
}
]
let searchString = "brand new car".split(" ") // ["brand", "new", "car"]
let filter = json.filter(json => searchString.includes(json.name))
if (filter.length) {
console.log(filter[0].name)
console.log(filter[0].Id)
}
else console.log("not found")

How to replace a JSON object value {} in Nodejs

I have the following JSON object data stored in a JSON file, which will be passed as a when performing an API call.
I want to replace "it-goes-here" with below {} block.
replaced-data:
{
"parenturl":"xxx.com",
"username":"userId",
"password":"xxx!",
"id":"id",
"url":"xxx.com",
"xxx":"xxx"
}
test.json
{
"details": it-goes-here,
"dbs": [
{
"schemas": [
{
"schemaName": "schemaName",
"tables": [
{
"tableName": "tableName",
"type": "table",
"columns": [
{
"name": "name",
"gender": "F",
"canDonate": true,
"database": "database"
},
etc.,
]
}
]
}
],
}
I have tried the code below, but it keeps giving me SyntaxError: Unexpected token
in JSON at position 28. I'm new to nodeJS, what am I doing here? What else can I try?
let data = await fs.readFileSync('./test/test.json', 'utf8').toString();
data = await JSON.parse(JSON.stringify(data).replace('it-goes-here', 'replaced-data'));
Try read and parse the test.json to JSON Object and run data.details = replacedData to replace the details object to replacedData object.

How To Add A String Inside An Object For The Given Example

Hi iam finding the best way to add a string inside the given object.Any help would be appreciated
my String is 'created'
Down Below Is My Data
{
"id": "222",
"list": [
{
"name": "Tony",
}
],
iam trying to insert 'created' in the data like this
{
"id": "222",
"list": [
{
"name": "Tony",
"type":"created"
}
]
The string you've provided looks a lot like JSON data. You can convert a JSON string to an actual javascript object by using the JSON.parse(string) method.
With this object we then can query it's list property - which in your case is an array of objects - and add a new property type to each of the arrays elements. The final step is converting the object back to a JSON string using the JSON.stringify(object) method.
Here's an example:
let str = `{
"id": "222",
"list": [
{
"name": "Tony"
}
]
}`;
let data = JSON.parse(str);
data.list.forEach(element => {
element.type = "created";
});
str = JSON.stringify(data);
console.log(str);
const myObj = {
"id": "222",
"list": [
{
"name": "Tony",
}
],
};
myObj.list[0].type = "created";
This is the way you can do this. But you'd better use secified index of list items;
const index = 0; // Or any other way to get this
myObj.list[index].type = "created";

Iterating over nested object

I have a nested object with structure as follows:
{
"sensors": [{
"probe": "PROBENAME",
"sensor": "SENSORNAME",
"status": "STATUS"
}, {
"probe": "PROBENAME",
"sensor": "SENSORNAME",
"status": "STATUS"
}]
}
Is there a good way to actually iterate over this in such a way that I only get the "probes" and "sensors." There are 1000s of each, and I want to be able to grab all of them. For some reason, whenever I iterate over the structure, I just get [object][object] in the return.
This? Or am I missing something?
yourObj.sensors.forEach(function(item){
console.log(item.probe, item.sensor);
});
newObj = {sensors: obj.sensors.map(({sensor, probe} => ({sensor, probe}))};
var input = {
"sensors": [{
"probe": "PROBENAME",
"sensor": "SENSORNAME",
"status": "STATUS"
}, {
"probe": "PROBENAME",
"sensor": "SENSORNAME",
"status": "STATUS"
}]
}
var output = []
input.sensors.forEach(function(sensor){
output.push({
probes : sensor.probe,
sensor : sensor.sensor
})
});
console.log(output)

Accessing JSON array's through object properites

Let's say I have the next JSON file:
{
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
}
I want to access the rating of a show, by it's name. Something like this:
var rating = data.shows["House of cards"].rating;
Is this possible? Or something similar?
Thanks a lot!
You won't have such hash-style access just by deserializing that JSON sample.
Maybe you might be able to re-formulate how the data is serialized into JSON and use object literals even for shows:
{
"shows": {
"House of cards": {
"rating": 8
}
}
}
And you can still obtain an array of show keys using Object.keys(...):
Object.keys(x.shows);
Or you can even change the structure once you deserialize that JSON:
var x = { shows: {} };
for(var index in some.shows) {
x.shows[some.shows[index].name] = { rating: some.shows[index].rating };
}
// Accessing a show
var rating = x.shows["House of cards"].rating;
I suggest you that it should be better to do this conversion and gain the benefit of accessing your shows using plain JavaScript, rather than having to iterate the whole show array to find one.
When you use object literals, you're accessing properties like a dictionary/hash table, which makes no use of any search function behind the scenes.
Update
OP has concerns about how to iterate shows once it's an associative array/object instead of regular array:
Object.keys(shows).forEach(function(showTitle) {
// Do stuff here for each iteration
});
Or...
for(var showTitle in shows) {
// Do stuff here for each iteration
}
Update 2
Here's a working sample on jsFiddle: http://jsfiddle.net/dst4U/
Try
var rating = {
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
};
rating.shows.forEach(findsearchkey);
function findsearchkey(element, index, array) {
if( element.name == 'House of cards' ) {
console.log( array[index].rating );
}
}
Fiddle
var data = {"shows": [{"name": "House of cards","rating": 8},{"name": "Breaking bad","rating": 10}]};
var shows = data.shows;
var showOfRatingToBeFound = "House of cards";
for(var a in shows){
if(shows[a].name == showOfRatingToBeFound){
alert("Rating Of "+ showOfRatingToBeFound+ " is " +shows[a].rating);
}
}

Categories