JSON format failing on JSONLint - javascript

I'm writing some functions that construct what should be a properly formatted JSON string which I can then parse into a JSON object.
My object is failing on JSONLint with the following error:
syntax error, unexpected TINVALID at line 2
[
SERVER: {
ip = 10.10.10.1,
port = 8100
},
TYPES: [
ssh,
shht
]
]
I assumed that this would give me an array of JavaScript objects.
Even if I did this instead (object instead of array):
{
SERVER: {
ip = 10.10.10.1,
port = 8100
},
TYPES: [
ssh,
shht
]
}
It doesn't work and I get the same error:
I assume that with the object, I would be able to access some data like so:
var serverIP = myObject.SERVER.ip;
That's certainly what I'd like to do.
Many thanks in advance,
Joe

You have to use quotation marks around the identifiers, and the values that are strings:
This is valid JSON:
{
"SERVER": {
"ip": "10.10.10.1",
"port": 8100
},
"TYPES": [
"ssh",
"shht"
]
}
If you are actually not using JSON at all, but just trying to create a Javascript literal object, then you should not use JSONLint to check the code.
This is valid Javascript:
var myObject = {
SERVER: {
ip: '10.10.10.1',
port: 8100
},
TYPES: [
'ssh',
'shht'
]
};

This validates:
{
"SERVER": {
"ip" : "10.10.10.1",
"port" : 8100
},
"TYPES": [
"ssh",
"shht"
]
}
you need double quotes around every string and since its an object you need : instead of =

your mixing json object with javascript arrays
this is json format
{
"item":"value",
"item2":"value"
}
and this would be a JavaScript array
[
"apple",
"orange"
]
os I think this is what you are looking for
{
"SERVER": {
"ip": "10.10.10.1",
"port": 8100
},
"TYPES": [
"ssh",
"shht"
]
};

Related

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 can I extract a json from a string in javascript

I need to extract json from a particular string which looks like this:
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]
I have tried this but could not extract it .
var regex=cookies.match(/{"seed":(\w|\W)*"channel":(\w|\W)*}/);
What is the solution I could use?
Thanks in advance:)
If you know there is only a single plain JSON object like this in the string, you can use this regex to capture the curly braces and everything in between:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
This is no way guarantees the string is valid JSON. So if you want to run JSON.parse on the result, be aware it will throw an error if the string is invalid.
For the loglocale:
let dataJSON = `
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]`
then:
let string = dataJSON.substring(
dataJSON.indexOf("loglocale=") + 10,
dataJSON.lastIndexOf("; regStatus")
)
JSON.parse(string);

How access nested JSON node after converting from SOAP?

Using node.js(javascript) how do I access the GetDataResult node in this JSON data that has been converted from SOAP data.
{
"s:Envelope": {
"$": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"s:Body": [{
"GetDataResponse": [{
"$": {
"xmlns": "http://tempuri.org/"
},
"GetDataResult": ["You entered: TEST"]
}]
}]
}
}
Test using nodejs interactive mode :
$ node
> var x = {
... "s:Envelope": {
..... "$": {
....... "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
....... },
..... "s:Body": [{
....... "GetDataResponse": [{
......... "$": {
........... "xmlns": "http://tempuri.org/"
........... },
......... "GetDataResult": ["You entered: TEST"]
......... }]
....... }]
..... }
... }
undefined
> console.log(x["s:Envelope"]["s:Body"][0]["GetDataResponse"][0]["GetDataResult"][0])
Output :
'You entered: TEST'
Explanations :
I try to elaborate a bit from comments below. There is no container, I try to explain :
You have to think json like what it is : an object or a data structure.
In python, we would say it's a dict, in perl a hash table etc... Globally, it's all about associative array
So when you see in JSON :
"key" : { "value" }
it's an associative array
If instead you see
"key": [
{ "key1": "foo" },
{ "key2": "bar" },
{ "key3": "base" }
]
It's an array of hashes or array of associative arrays.
When you access a simple associative array without spaces or odd characters, you can (in js do :
variable.key
In your case, you have odd character : in the key name, so x.s:Envelope wouldn't work. Instead we write: x['s:Envelope'].
And as far as you have arrays of associative arrays inside [], you have to tell js which array number you need to fetch. It's arrays with only one associative array, so it's simple, we go deeper in the data structure by passing array number, that's what we've done with
x['s:Envelope']["s:Body"][0]
^
|

How to parse a JSON array string in 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']

Javascript JSON syntax

HI I am trying to create a JSON file in which I want to store some data for different files. The problem is I cannot figure the correct syntax. Here is what I have so far:
var object = {
"id-1" :[
{
"type":"Corporate Website",
"tech":"HTML" ,"CSS" , "Javascript/jQuery"
}
],
"id-2" :[
]
}
I seem to be getting an error at "tech".If that is not corect how can I enumarate multiple elements?I am sorry for the noob question I have been using javascript for a short period of time and I am still very confused with the language.
{
"id-1": [
{
"type": "Corporate Website",
"tech": [
"HTML",
"CSS",
"Javascript/jQuery"
]
}
],
"id-2": []
}
Note the array like syntax for "tech".
Tech should be an array (enclosed in square brackets):
"tech": ["HTML", "CSS", "Javascript/jQuery"]
Source:
An array is an ordered collection of values. An array begins with [
(left bracket) and ends with ] (right bracket). Values are separated
by , (comma).
http://www.json.org/

Categories