Create JSON from a String - json

I am trying to create a json from this String
var json = { data: [v1,v2], con: [begin: "test1", end: "test2"] };
What is wrong with the String? I get an error SyntaxError: Unexpected token :It is not possible to set a key for the value test1 and test2?

In JavaScript:
An object literal, which uses the {} syntax, consists of a collection of property: value pairs.
An array literal, which uses the [] syntax, consists of a collection of values.
[begin: "test1", end: "test2"]
You have used the array syntax here, but have tried to put property: value pairs inside it.
This causes your error, the : isn't expected.
You probably want to use the {} there. Alternatively, you want to remove begin: and end:.
This has nothing to do with JSON or strings. It is simply JavaScript.

You are instantiating a javascript Object.
const toto = {};
is the same as
const toto = new Object();
This is a String javascript object, which hold a string representation of a json.
const toto = "{ \"key\": \"value\" }";

Try
var json = { data: ["v1","v2"], con: [{begin: "test1"}, {end: "test2"}] };
It looks like you might have a blocking error.

Related

Is it possible to iterate over a json object having `\n` and \`` characters in typescript?

I have a json object which is something like below:
"\"{\\n \\\"Foo\\\" : \\\"1234\\\",\\n}\""
Is it somehow possible to iterate through this json object?I tried but my logic did not work which i feel is basically because of these \n and \ i am unable to iterate.How can i get rid of these unnecessary characters ?
The string you've shown is double-encoded JSON if we assume that you've removed some of the content (it has a trailing , in the JSON, which JSON doesn't allow).
If you run it through JSON.parse, you get a string containing JSON for an object.
If you run that through JSON.parse, you get an object.
E.g.:
const parsedOnce = JSON.parse(str);
const obj = JSON.parse(parsedOnce);
Then you loop through that object's properties in the normal way (for-in, Object.keys, Object.entries, etc.).
Live Example:
const str = "\"{\\n \\\"Foo\\\" : \\\"1234\\\"\\n}\"";
const parsedOnce = JSON.parse(str);
const obj = JSON.parse(parsedOnce);
for (const key in obj) {
console.log(`${key} = ${obj[key]}`);
}
That code is also valid TypeScript (playground link), though if you have a type you can apply to obj so it doesn't default to any, that would be good. (You could apply {[key: string]: any} to it at minimum.)

How to read a JSON object with a full-stop in the name using POSTMAN?

I have a problem trying to check a JSON value in the response body using POSTMAN because the JSON object name has a full-stop in it
Usually a JSON response body would be something like this:
{
"restapi": "Beta",
"logLevel": "INFO"
}
So normally we can do a test on the JSON value like this using POSTMAN:
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.restapi).to.eql(Beta);
});
But the problem I'm having now is that the JSON object name has a full stop like this
{
"restapi.name": "Beta",
"logLevel.sleep": "INFO"
}
So if I try to do read the object like this, it will come out with an error
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.restapi.name).to.eql(Beta);
});
You can just reference the key value by using brackets around the name:
jsonData["restapi.name"]
object properties can be accessed with . operator or with associative array indexing using []. ie. object.property is equivalent to object["property"]
this should do the trick
jsonData["restapi.name"]

Unnable to read json response in reactjs

I need to replace a value in the response ,
My Json format :
{"Message":"","IsSuccessful":true,"sample2.0com":["data1","data2"],"sample1.0com":["data3","data4","data5","data6"]}}
When I am trying to read the above response , I am facing issue
let sample2 = response.data.Result.sample2.0com;
Please give me a solution to read sample2.0com components from the response
Keys that are not valid JavaScript variable names (start with one of a-zA-Z_$ and contain only a-zA-Z0-9_$) must be accessed as strings inside square brackets ([]).
For example: obj.camelCase is OK, but obj.this key contains spaces is not OK - it would have to be obj['this key contains spaces'].
JSON objects are surrounded by curly braces {}.
You can access the object values by using dot . notation:
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
You can also access the object values by using bracket ([]) notation:
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
Similarly you can use as like above
responseData = {"Message":"","IsSuccessful":true,"sample2.0com":["data1","data2"],"sample1.0com":["data3","data4","data5","data6"]}}
let sample2 = responseData["sample2.0com"];
This will fix yours
Is because of your . in the sample2.0com.. you have to use the [] to call the property, so use response.data.Result['sample2.0com'], but I am not sure what is the "Result" object ... maybe you should use response.data['sample2.0com']

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

Flash: Parsing a JSON file that has a node called Class

Essentially I'm trying to parse JSON and assigning the results to variables, one of which is "var = JSON.class;" with class being what's returned in the JSON. However, flash won't let me parse it because it's called class which it uses to create new classes. Is there any workaround or will I not be able to grab this node?
I'm not sure if this is what you're asking, but if you have a property in your JSON object named "class", you should be able to parse it like as shown below.
// assuming JSON object looks like this, and is stored in a var named 'jsonData'
var jsonData:Object = { "id": 0, "class": "MyClassName", "values": [1,2,3] }
// trying to parse like this won't work w/keywords like 'class':
var parsedValue : String = jsonData.class;
// parse it with this way, using the square brackets:
var parsedValue : String = jsonData["class"];