Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert text to json object in JavaScript

Shulou Source: shulou.com Published: 2022-06-01 10:31:04 09月21日 Update

Most people do not understand the knowledge points of this article "how to convert text into json objects in JavaScript", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to convert text to json objects in JavaScript" article.

The JSON array is written in square brackets.

Like JavaScript, arrays can contain objects:

"employees": [

{"firstName": "Bill", "lastName": "Gates"}

{"firstName": "Steve", "lastName": "Jobs"}

{"firstName": "Alan", "lastName": "Turing"}

]

In the above example, the object "employees" is an array. It contains three objects.

Each object represents a record of a person (with a first and last name).

Convert JSON text to JavaScript object

The common use of JSON is to read data from a web server and then display the data in a web page.

For simplicity, you can use a string as an input demonstration.

First, create a JavaScript string that contains the JSON syntax:

Var text ='{"employees": ['+

'{"firstName": "Bill", "lastName": "Gates"},' +

'{"firstName": "Steve", "lastName": "Jobs"},' +

'{"firstName": "Alan", "lastName": "Turing"}]}'

Then, use JavaScript's built-in function JSON.parse () to convert the string to a JavaScript object:

Var obj = JSON.parse (text)

Finally, use this new JavaScript object in your page:

Example

Document.getElementById ("demo") [xss_clean] =

Obj.employees [1] .firstName + "" + obj.employees [1] .lastName

The above is about the content of this article on "how to convert text into json objects in JavaScript". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Tags: Objects content text characters strings arrays data articles knowledge articles three individuals representatives values examples functions most examples that is square brackets Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker macOS vpn Shulou Tech Info Shulou Information