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.
Related
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";
Using the same code from https://docs.cypress.io/api/commands/writefile.html#Flags
const filename = '/path/to/list.json'
cy.readFile(filename).then((list) => {
list.push({ item: 'example' })
// write the merged array
cy.writeFile(filename, list)
})
#system throws:
list.push is not a function
fixture file:/path/to/list.json
{
"details": {
"name": "abc",
"age": 20
}
}
expecting the list.json output as
{
"details": {
"name": "abc",
"age": 20
},
"item": "example"
}
Has anyone tried to append an existing JSON file with the above code snap?
If so please share with me your experience.
Thanks
.push() is for arrays, but you have an object in your JSON file. Use list.item ='example'; to set a new property on an object.
enter image description herebelow code snippet for getting json data from iron ajax call . i am able to get json object value in mapResponse.
i want to get the value of results array which is in json data and want to pass this results object value in another polymer component as a input attribute
code for loading data from iron ajax
<iron-ajax
id="originalData"
auto
url="{{originalDataURL}}"
handle-as="json"
last-response="{{originalData}}" on-response="mapResponse">
</iron-ajax>
Json file
{
"tags": [
{
"name": "test",
"results": [
{
"groups": [
{
"name": "type",
"type": "number"
}
],
"values": [
[
946890000000,
99.93584833,
3
],
[
946846800000,
99.94809842,
3
],
[
946803600000,
99.96034846,
3
],
[
946760400000,
99.97259848,
3
],
[
946717200000,
99.98484848,
3
]
],
"attributes": {}
}
],
"stats": {
"rawCount": 5
}
}
]
}
<script>
Polymer({
is: 'test-view',
properties: {
results: {
type: Array
},
mapResponse: function (data) {
var dummy = data.detail.response;
console.log("resposne is ",dummy);
results = dummy.results;
console.log("array is ",results);
},
i tried to get results array object value as above in console logs but getting undefined. here i am able to get the value of dummy where i am getting full json object (tags) i want to get only results array object from this (tags )object .
can anyone please suggest me how can i get only results array value ??
Thanks in advance.
It should be results = dummy.tags[0].results;
instead of results = dummy.tags[0].results;.
Or you can do results = dummy.tags.map(x=>x.results); if tags have multiple arrays of results.
I am using the node.js package xml2js to transform xml into json.
Documentation is here: https://www.npmjs.com/package/xml2js
My problem is that attributes for those xml are not correctly transformed.
example XML with multiple events
<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5">
Result from JSON.stringify(result.search.events)
The event tag is only once in the generated JSON - My expectation is that it should have multiple tags event. So I assume the transformation process went wrong. I tried multiple options for the parser like ignoreAttrs, explicitArray or explicitChildren but without success.
[{
"event": [{
"$": {
"id": "E0-001-098932239-8"
},
]
}, {
"$": {
"id": "E0-001-105389601-2"
},
}, {
"$": {
"id": "E0-001-104342965-3"
},
}, {
"$": {
"id": "E0-001-104830349-3"
},
access JSON elements
After correct transformation I expect to simply access the JSON elements via event[1].$.id
but all tries are unsuccessful:
events.event --> undefined
events.event.$ --> undefined
events.$ --> undefined
My Question is now: how can i correctly transform the xml into JSON and access the elements correctly?
Javascript is starting from 0, you should get events[0].event[0].$.id
Also, you can try with another package (camaro) with simply and easily change the desired result.
Example:
const xml = '<events><event id="E0-001-098932239-8"></event><event id="E0-001-105389601-2"></event><event id="E0-001-104342965-3"></event><event id="E0-001-104830349-3"></event><event id="E0-001-105374979-6"></event><event id="E0-001-105389620-7"></event><event id="E0-001-104247759-2"></event><event id="E0-001-104342949-5"></event></events>'
const temp = {
events: ['/events/event', {
id: '#id'
}]
}
const transform = require('camaro')
const results = transform(xml, temp)
console.log(JSON.stringify(results, null, 2))
Results
{
"events": [
{
"id": "E0-001-098932239-8"
},
{
"id": "E0-001-105389601-2"
},
{
"id": "E0-001-104342965-3"
},
{
"id": "E0-001-104830349-3"
},
{
"id": "E0-001-105374979-6"
},
{
"id": "E0-001-105389620-7"
},
{
"id": "E0-001-104247759-2"
},
{
"id": "E0-001-104342949-5"
}
]
}
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']