-1

I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesnt work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.

I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.

So I deduced the problem is not with the string. How do i convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesnt work.

Screenshot of console log: enter image description here

Advance Thanks

Om Chaturvedi
  • 103
  • 1
  • 2
  • 10
  • 5
    Possible duplicate of [Converting a string to JSON object](https://stackoverflow.com/questions/10976897/converting-a-string-to-json-object) – Nisarg Shah Aug 05 '17 at 06:18
  • You parse string to json when pass string refere this question https://stackoverflow.com/questions/18745406/how-to-check-if-its-a-string-or-json – Araf Aug 05 '17 at 06:21
  • `So I deduced the problem is not with the string` - you'd be wrong, because if the string is exactly what is shown as `json1` in the *image*, then that is NOT JSON at all - how about you post, as **text** the **exact** string you're having an issue with – Jaromanda X Aug 05 '17 at 06:30
  • @ Jaromanda...please find exact string.... { "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] } – Om Chaturvedi Aug 05 '17 at 06:45
  • What's this function you're using? What does "doesn't work" *mean*? – nitind Aug 05 '17 at 07:05

2 Answers2

-1

JavaScript is a dynamically typed language, so you can't really specify types of function arguments up front. If you want that, look into TypeScript.

JSON is nothing but a String, not a standalone type in JavaScript. To convert a JavaScript object to the equivalent JSON string representation use:

const myJSON = JSON.stringify ({ a: 'b' })

To get a JavaScript object back from a JSON string use:

JSON.parse (myJSON)

When going over the network, libraries can automatically return serialized objects if you specify the type as JSON. You haven't pasted any code, so I'm guessing that you haven't specified application/json as the Content-Type in your network request. Since you've tagged your question jQuery, take a look at [$.getJSON][2], this should do what you want.

Prajjwal
  • 1,055
  • 2
  • 10
  • 17
-2

Use JSON.parse

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

Example:

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

str = '{"a":1, "b":2}';
console.log(isJson(str)); // true

str1 = '{["a":1, "b":2]}';
console.log(isJson(str1)); // false
Chandra Kumar
  • 4,127
  • 1
  • 17
  • 25