Unnable to read json response in reactjs - json

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']

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.)

Ambiguous format output in nodejs

I am having output in following format as
"[{"a":"a1"},{"a":"a2"}]"
I want to actually extract it in array of json:
[
{
"a":"a1"
},
{
"a":"a2"
}
]
How to convert it?
You have tagged this with Node-RED - so my answer assumes that is the environment you are working in.
If you are passing a message to the Debug node and that is what you see in the Debug sidebar, that indicates your msg.payload is a String with the contents of [{"a":"a1"},{"a":"a2"}] - the Debug sidebar doesn't escape quotes when displaying strings like that.
So you likely already have exactly what you want - it just depends what you want to do with it next.
If you want to access the contents you need to parse it to a JavaScript Object. You can do this by passing your message through a JSON node.
Assuming your input contains the double quotes in the beginning and end, it is not possible to directly JSON.parse() the string.
In your case, you need to remove the first and last character (the double quotes) from your string before parsing it.
const unformattedString = '"[{"a":"a1"},{"a":"a2"}]"'
const formattedString = unformattedString.substr(1, unformattedString.length - 2)
const json = JSON.parse(formattedString)
The variable json now contains your JSON object.
I would suggest a different method which will get your work done without using any third party library.
var a = '[{"a":"a1"},{"a":"a2"}]';
var b = JSON.parse(a);
console.log(b); // b will return [{"a":"a1"},{"a":"a2"}]
Another way which is eval function which is generally not recommended
var d = eval(a);
If you want to use JQuery instead use :
var c = $.parseJSON(a);

Create JSON from a String

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.

Is ID.X a valid JSON key - cannot parse it with newtonsoft library

I am using NewtonSoft to manage a ResJson string.
I want to retrieve an item from this string:
{
"ID.1": "File and Menu",
"ID_2": "Test Scenario"
}
var jtok = JObject.Parse(ResJsonText).SelectToken(pair.Key);
retrieves only the second item.
I have the latest newtonsoft.json.dll version.
Is the ID valid?
I have tested it on jsonlint.com and it says it is valid.
Yes, the key is valid, but you cannot use a key with a . in the SelectToken method, because the . has special meaning as a navigation operator to that method. In this case ID.1 would mean "find a property called ID then navigate to its child object and find a property called 1, then get its value. Since that arrangement does not exist in your JSON, you get a null value.
Instead, you can use square bracket syntax:
JObject obj = JObject.Parse(json);
JToken token = obj["ID.1"];
If you are looping through key-value pairs on a JObject (which I suspect you are), then you don't need to use the keys to get the values; you already have them in the Value property on the pairs:
string json = #"{ ""ID.1"": ""File and Menu"", ""ID_2"": ""Test Scenario"" }";
var jo = JObject.Parse(json);
foreach (var pair in jo)
{
Console.WriteLine(pair.Key);
Console.WriteLine(pair.Value));
}
Fiddle: https://dotnetfiddle.net/fpcMGk

JSON.parse: expected property name or '}'

Data contains (/"/):
{"test":"101","mr":"103","bishop":"102"}
script:
console.log($.parseJSON(result));
I'm getting error,
JSON.parse: expected property name or '}'.
Had same issue when used single quotes in JSON file, changed to double quotes for all string properties/values and it's working OK now.
Change:
JSON.parse("{'wrongQuotes': 5}")
To:
JSON.parse('{"rightQuotes": 5}')
If you're receiving the JSON with the encoded ", you'll have to replace each instance of " with a true " before doing JSON.parse. Something like:
myJSONstring.replace(/"/ig,'"');
My case was even simpler.
Having confused JSON with plain JS, I didn't put the object keys in double quotes.
❌:
{
title: "Hello World!"
}
✅:
{
"title": "Hello World!"
}
The irony is, Postman even highlighted this to me, but I ignored. Sleep is the answer.
For anyone who is using laravel blade and declaring a JS variable in a view.
You need to use:
var json = JSON.parse('{!! $json !!}');
Otherwise you will get this error due to the quotes being parsed as "
Change
{"test":"101","mr":"103","bishop":"102"}
To
'{"test":"101","mr":"103","bishop":"102"}'
if this is coming from the server (PHP)
i.e <?php $php_var = ["test" => "101", "mr" => "103", "bishop" => "102"]?>
then on Javascript end
var javascript_var = $.parseJSON('<?= json_encode($php_var) ?>');
/* suppose your json are single quote, it's necessary replace it single quote before, a simple example*/
let ojson = "{'name':'peterson'}";
ojson = ojson.replace(/'/g, '"');
ojson = JSON.parse(ojson);
console.log(ojson['name'])
for example, if u get something like this
{ "location": "{'lat': 4.6351144, 'lng': -74.12011199999999}" }
from your server, or recently get a bad converted format.
first,get your string
myItemString = "{'lat': 4.6351144, 'lng': -74.12011199999999}"
and change the keys using replace, and later json.parse,
'key' to ---> "key"
const key1 = myItemString.replace("'lat'",'"lat"')
const key12 = key1.replace("'lng'", '"lng"');
const obj = JSON.parse(key12)
console.log(obj)
You can try using stringifying before parsing:
JSON.parse(JSON.stringify(result))